我想将一个类的实例添加到arraylist。这是代码:
ArrayList<Edge> edges = new ArrayList<Edge>(); //A List Containing All the Edges & their startNode,endNode
System.out.println("Enter Number of Nodes: ");
int noOfNodes = scan.nextInt(); //Gets Number of Nodes in Graph
int graphmatrix[][] = new int[noOfNodes][noOfNodes]; //Makes a Matrix According to Graph
for ( int i=0; i < noOfNodes; i++ ) {
for (int j=0; j < noOfNodes; j++) {
if ( j > i ) {
System.out.println("Enter Relation Between " + i + " & " + j + ": ");
int length = scan.nextInt();
graphmatrix[i][j] = length;
graphmatrix[j][i] = length;
Edge edge = new Edge(i, j, length);
edges.add(edge);
}
}
}
System.out.println(edges);
这是最后一行的输出:
如您所见,[dijkstra.Edge@49e4cb85,dijkstra.Edge@2133c8f8,dijkstra.Edge@43a25848]
问题似乎在于它没有创建arraylist。 我不明白怎么了。 这也是Edge类的构造函数:
public Edge(int startNode, int endNode, int length) {
this.startNode = startNode;
this.endNode = endNode;
this.length = length;
}