向图表添加顶点

时间:2013-03-02 18:47:16

标签: java graph

我想从文件中读取数据并从中构建图表。我做了所有事情,所有顶点都是正常创建的,但是当我将它们添加到图形时,它们的相邻列表(它们是地图,其键值是邻近顶点的数字,值是它们的距离)变空。任何人都可以告诉我的代码有什么问题吗?

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时,没关系,但是当我打印图形时,所有相邻的列表都是空的。有什么问题?

1 个答案:

答案 0 :(得分: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);
}

你不应该清除它,清除它,好吧......清除它。