[英]How two swap two elements in a array list without using collections.swap method
[英]Collections.swap() in java swap everything in the method
我正在嘗試編寫簡單的代碼來交換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";
}
您聲明了引用clone1
和clone2
引用與v
相同的對象(並丟棄了剛創建的new Vector()
)。
對對象使用賦值運算符=
不會克隆該對象。 它只是引用了另一個引用來引用相同的對象。
v ----> Vector object
^
clone1 --+
您可以通過說出創建Vector
的副本
Vector clone1 = new Vector(v);
視覺...
v ----> Vector object
clone1 ----> Cloned Vector object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.