我正在尝试从文件中读取以创建HashMap<String, HashMap<String, Integer>>
.
inputFile 的格式如下:
A B C D
1 -1 2 -3
2 3 -5 3
-3 2 7 -5
4 3 1 1
此输入文件表示所有点对之间的距离。这意味着,它表示以下矩阵:
A B C D
A 1 -1 2 -3
B 2 3 -5 3
C -3 2 7 -5
D 4 3 1 1
在创建地图时,当我打印键和值时,会打印正确的值。但是当我在完全填充地图后尝试打印地图时,它只会正确打印外部地图的键。其他所有内容都打印为null
.
我究竟做错了什么?
public static HashMap<String, HashMap<String, Integer>> initMap() {
HashMap<String, HashMap<String, Integer>> distancesMap = new HashMap<String, HashMap<String, Integer>>();
final String distancesFileName = "/home/name/workspace/Tester/src/main/distances.txt";
String distancesFile = Main.readInputFile(distancesFileName);
String[] distancesFileArray = distancesFile.split("\n");
String[] firstLine = distancesFileArray[0].split("\t");
for(int iii = 1; iii < distancesFileArray.length; iii++) {
HashMap<String, Integer> tempMap = new HashMap<String, Integer>();
String[] singleLineArray = distancesFileArray[iii].split("\t");
for(int jjj = 0; jjj < singleLineArray.length; jjj++) {
tempMap.put(firstLine[jjj], Integer.parseInt(singleLineArray[jjj]));
// the following print statement (commented out) prints the correct values
// System.out.println(firstLine[jjj] + " " + tempMap.get(firstLine[jjj]));
}
distancesMap.put(firstLine[iii - 1], tempMap);
}
/*
* The following lines just print the key of the outer map correctly
* but everything else is printed as null
*/
for(String key : distancesMap.keySet()) {
System.out.print(key + "\t"); // prints the correct String value
HashMap<String, Integer> tempMap = distancesMap.get(key);
for(String innerKey : tempMap.keySet()) {
// the following line only prints null values
System.out.print(tempMap.get(innerKey + "\t"));
}
System.out.println();
}
return distancesMap;
}
我从中得到的输出是这样的:
B nullnullnullnull
C nullnullnullnull
D nullnullnullnull
A nullnullnullnull