首先让我说我有一个文件。有关更多信息,请在此处查看。
我已经在哈希图上添加了多个值的边缘。我通过添加这段代码来检查它:
map.put(nodes.get(i), edges);
System.out.println(nodes.get(i) + " " + map.get(nodes.get(i)));
将每个条目添加到地图后,我会立即检查它是否已成功添加。是的,它奏效了。
这是输出:
a0 [acodijkstra.Edge@b1c5fa]
a1 [acodijkstra.Edge@13caecd, acodijkstra.Edge@f84386, acodijkstra.Edge@1194a4e]
a2 [acodijkstra.Edge@15d56d5, acodijkstra.Edge@efd552, acodijkstra.Edge@19dfbff]
a3 [acodijkstra.Edge@10b4b2f, acodijkstra.Edge@750159, acodijkstra.Edge@1abab88]
但是在创建另一个显示地图内容的方法时,我发现地图是空的。这是代码:
public void viewFile() {
for(int i=0; i<nodes.size();i++) {
System.out.println(nodes.get(i) + " " + this.map.get(nodes.get(i)));
}
}
上面代码的输出是这样的:
a0 []
a1 []
a2 []
a3 []
这可能是什么原因?我真的很困惑为什么会这样。
对于代码,这是简化版本(如果遵守,这将导致错误,因为我编辑了一些被认为不必要的部分):
class Reader {
HashMap<String, Vertex> vertexList;
Map<String, ArrayList<Edge>> map;
ArrayList<String> nodes;
ArrayList<Edge> edges;
public Reader(String fileName) {
vertexList = new HashMap<String, Vertex>();
map = new HashMap<String, ArrayList<Edge>>();
nodes = new ArrayList<String>();
edges = new ArrayList<Edge>();
readFile(fileName);
}
private void readFile(String fileName) {
try{
FileReader file = new FileReader(fileName);
Scanner sc = new Scanner(file);
int i = 0;
while (sc.hasNextLine()) {
input.add(sc.nextLine());
i++;
}
setNodes();
setVertices();
System.out.println();
file.close();
} catch(Exception e){
System.out.println(e);
}
}
public void setNodes() {
System.out.println();
for(int i=0; i<input.size(); i++) {
line = this.input.get(i);
nodes.add(line.substring(0,line.indexOf("-")).trim());
adjLine.add(line.substring(line.indexOf("-")+1).trim());
}
}
private void setVertices() {
String[] listEdges;
for(int i=0; i<nodes.size(); i++) {
//if vertex does not exist, create it
if(vertexList.containsKey(nodes.get(i))) {
vertexList.put(nodes.get(i), new Vertex(nodes.get(i)));
}
line = adjLine.get(i);
//separate adj edges to *
if(line.contains("*")) {
listEdges = line.split("\\*");
} else {
listEdges = new String[1];
listEdges[0] = line;
}
//add edges to specified vertex
for(int j=0; j < listEdges.length; j++ ) {
String[] word = listEdges[j].split(",");
edges.add(new Edge(vertexList.get(word[0]),Double.parseDouble(word[1])));
}
map.put(nodes.get(i), edges);
System.out.println(nodes.get(i) + " " + map.get(nodes.get(i)));
edges.clear();
}
}