-1

我想从文件中读取数据并从中构造一个图表。我做了一切,所有的顶点都是正常创建的,但是当我将它们添加到图中时,它们的相邻列表(这是地图,其键值为相邻顶点的编号,值是它们的距离)变为空。谁能告诉我的代码有什么问题?

public class Vertex {
private int number;
private LinkedHashMap<Integer, Integer> adjacent;

public Vertex(int num) {
    this.number = num;
    this.adjacent = new LinkedHashMap<Integer, Integer>();
}

}

public class Graph {
private ArrayList<Vertex> vertices;
private int verticesSize = 201;

public Graph() {
    Vertex initialVertex = new Vertex(0);
    this.vertices = new ArrayList<Vertex>();
    for(int i = 0; i < verticesSize; i++) {
        vertices.add(i, initialVertex);
    }

}

}

public class Test {

public static void printGraph(Graph graph) {
    for(int i = 0; i < graph.getVerticesSize(); i++)
            System.out.println(graph.getVertices().get(i));
}

public static void main(String[] args) throws IOException {
    FileInputStream fStream = new FileInputStream("C:/Lusine/Programming/Java/dijkstraData.txt");
    // Use DataInputStream to read binary NOT text.
    BufferedReader bReader = new BufferedReader(new InputStreamReader(fStream));

    Graph graph = new Graph();
    String[] maps;

    String line;
    LinkedHashMap<Integer, Integer> currentMap = new LinkedHashMap<Integer, Integer>();

    while( (line = bReader.readLine()) != null) {
         maps = line.split("\t");
         int firstDigit = Integer.parseInt(maps[0]);

          Vertex v = new Vertex(firstDigit);

          for(int i = 1; i < maps.length; i++) {
             String[] vertexDistance = maps[i].split(",");
             int vertex = Integer.parseInt(vertexDistance[0]);
             int distance = Integer.parseInt(vertexDistance[1]);
             currentMap.put(vertex, distance);
          }

            v.setAdjacent(currentMap);
            graph.getVertices().set(firstDigit, v);
            System.out.println("\n" + firstDigit +"-th vertex is\n" + v);
            currentMap.clear();

    }
    printGraph(graph);
}

当我打印 v 时,没关系,但是当我打印图形时,所有相邻列表都是空的。有什么问题?

4

1 回答 1

1

你的循环归结为

LinkedHashMap<Integer, Integer> currentMap = new LinkedHashMap<Integer, Integer>();

while ( ... ) {
     Vertex v = new Vertex(...);
     v.setAdjacent(currentMap);
     currentMap.clear();
}

因此,您在每个顶点中存储相同的相邻顶点映射,并在每次迭代结束时清除此映射。很明显,所有顶点在循环结束时共享相同的空地图。

您应该在每次迭代时创建一个新的 LinkedHashMap:

while ( ... ) {
    LinkedHashMap<Integer, Integer> currentMap = new LinkedHashMap<Integer, Integer>();
    Vertex v = new Vertex(...);
    v.setAdjacent(currentMap);
}

你不应该清除它,因为清除它,嗯……清除它。

于 2013-03-02T18:53:38.570 回答