图形测试=新图形(testVertices,testEdges); 我为什么得到以下结果有点困惑:
List<Vertex> temp = test.getVertices();
System.out.println(testVertices.size()); //size is 10 as expected
System.out.println(temp.size()); //size is now 0... but should be 10
这是我在下面的getVertices()方法
public List<Vertex> getVertices(){
List<Vertex> theVertices = new ArrayList<Vertex>();
for(int i=0;i<V.size();i++){
System.out.println("happen");//never reached...
theVertices.add(V.get(i));
}
return theVertices;
}
当我打电话给temp.size()时,我应该得到10,但我不明白为什么我会得到0.有人可以解释一下吗?
感谢。
Editted
import java.util。*; 公共类图{
private ArrayList<Vertex> V;
private ArrayList<Edge> E;
//constructor
public Graph(Collection<Vertex> v, Collection<Edge> e){
V=new ArrayList<Vertex>();
E=new ArrayList<Edge>();
}
public List<Vertex> getVertices(){
List<Vertex> theVertices = new ArrayList<Vertex>();
for(int i=0;i<V.size();i++){
System.out.println("happen");
theVertices.add(V.get(i));
}
return theVertices;
}
public static void main(String[] args){
Vertex A = new Vertex("A");
Vertex B = new Vertex("B");
Vertex C = new Vertex("C");
Vertex D = new Vertex("D");
Vertex E = new Vertex("E");
Vertex F = new Vertex("F");
Vertex G = new Vertex("G");
Vertex H = new Vertex("H");
Vertex I = new Vertex("I");
Vertex J = new Vertex("J");
List<Vertex> testVertices = new ArrayList<Vertex>();
testVertices.add(A);
testVertices.add(B);
testVertices.add(C);
testVertices.add(D);
testVertices.add(E);
testVertices.add(F);
testVertices.add(G);
testVertices.add(H);
testVertices.add(I);
testVertices.add(J);
Graph test = new Graph(testVertices, testEdges);
List<Vertex> temp = test.getVertices();
System.out.println(testVertices.size());
System.out.println(temp.size()); //size is now 0...
for(int i=0;i<temp.size();i++){
System.out.println(temp.get(i).getLabel());
}
答案 0 :(得分:2)
您可能希望在构造函数中执行的操作是复制参数:
//constructor
public Graph(Collection<Vertex> v, Collection<Edge> e){
V=new ArrayList<Vertex>( v );
E=new ArrayList<Edge>( e );
}
如果你不想要你自己的副本,但更喜欢保持顶点和边缘的集合在参数中传递,那么你应该做@Bhesh Gurung提出的建议,但这对我来说不太好,因为你可以&# 39;确保在构建图形对象后,有人不会修改顶点或边的列表。