我正在尝试编写一个简单的代码,用于交换Vector中的元素(方法中还有其他不相关的行用于其他目的,所以请忽略它们)。但是,当我调用Collections.swap(clone1,6,3)时,它会更改" v"矢量以及!!我做错了什么?
方法:
public static String DFS(Vector v){
Vector clone1 = new Vector();
clone1 = v;
Vector clone2 = new Vector();
clone2 = v;
// In order to compare goal is reached or not I created a goal vector
Vector solution = new Vector(9,0);
for(int i = 0; i < 9; i++)
solution.addElement(i);
if(v.isEmpty()){
return "Empty!!";
}
if(v.equals(solution)){
return "Solution!!!";
}
// In order to determine where the blank is
int indexOfZero = 0;
// Since this Depth-First Search, I am using stack as frontier
Stack s = new Stack();
indexOfZero = v.indexOf('0');
if (indexOfZero == 6){
Collections.swap(clone1,6,3);
Collections.swap(clone2,6,7);
}
//for(int i = 0; i < list.size(); i++){
// s.push(list.get(i));
// System.out.println("Stack in for loop");
//}
//Vector a = (Vector)s.pop();
System.out.println("\nElements after DFS:");
System.out.println(v.toString());
System.out.print("THIS IS MY ClONE 1: ");
System.out.println(clone1.toString());
System.out.print("THIS IS MY ClONE 2: ");
System.out.println(clone2.toString());
System.out.println();
return "a";
}
答案 0 :(得分:4)
您声明引用clone1
和clone2
引用与v
相同的对象(并放弃了刚创建的new Vector()
)。
将赋值运算符=
与对象一起使用不会克隆该对象;它只是引用另一个引用来引用同一个对象。
v ----> Vector object
^
clone1 --+
您可以通过
创建Vector
的副本
Vector clone1 = new Vector(v);
...视觉
v ----> Vector object
clone1 ----> Cloned Vector object