【问题标题】:Add hashmap in to hashmap as avalue将 hashmap 作为值添加到 hashmap
【发布时间】:2018-11-27 12:20:36
【问题描述】:

在下面的代码中,我创建了一个临时哈希映射并将其作为值添加到另一个哈希映射,在 while 循环结束时,csvList 哈希映射只有临时哈希映射的最后一个值作为值添加,所有其他值为空

键被保留,所有值都被 null 替换。 我在这里做错了什么,是 temp.clear 还是 temp hashmap 的声明位置。

HashMap<String, HashMap<String, String>> csvList = new HashMap<String, HashMap<String, String>>();

HashMap<String, String> tempMap = new HashMap<String, String>();
List<String> line = null;
try {
    inputStream = new FileInputStream(csvFile);

    //scanner = new Scanner(inputStream);
    scanner = new Scanner(inputStream, "UTF-8");
    //scanner.useDelimiter("\r\n");

    int i = 0;
    while (scanner.hasNext()) {
        //tempMap.clear();
        if (i == 0) {
            headList = parseLine(scanner.nextLine());
            i++;
        } else {
            line = parseLine(scanner.nextLine());
            pKey = "";

            for (int j = 0; j < line.size(); j++) {
                if (!selectClause.toLowerCase().contains(headList.get(j).toLowerCase()))
                    continue;
                else {
                    // Change for multiple PKeys
                    if (primaryKey.toLowerCase().contains(headList.get(j).toLowerCase())) {
                        pKey = pKey + line.get(j);
                    }
                    if (headList.get(j).equalsIgnoreCase(primaryKey))
                        pKey = line.get(j);
                    tempMap.put(headList.get(j).toLowerCase(), line.get(j));
                }
            }
            //System.out.println(i++);
            line.clear();
            csvList.put(pKey, tempMap);
        }
        //tempMap.clear();

    }
    headList.clear();
    //tempMap.clear();
    scanner.close();
    }

    return csvList;
}

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    您在 while 循环之外创建 tempMap,因此它是您一直使用的同一个实例,将创建移动到循环内,以便 csvList 中的每个 pKey 获得一个唯一实例

    while (scanner.hasNext()) {
        HashMap<String, String> tempMap = new HashMap<String, String>();
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多