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