【发布时间】: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;
}
【问题讨论】: