问题描述
我正在用 Java 编程,我想备份 ArrayList
在我清理它之前不幸的是,在我调用 clear()
之后,备份也被清理了.我该如何解决?
I'm programming in Java and I would like to take a backup of an ArrayList
before I clean itUnfortunately, after I call clear()
, the back up is cleaned as well.How can I solve that?
我的程序如下:
public class Main {
public static void main(String args[]) {
ArrayListMethod ALM = new ArrayListMethod();
ALM.FillArrayList();
}
}
import java.util.ArrayList;
public class ArrayListMethod {
public void FillArrayList() {
ArrayList AL;
AL = new ArrayList();
ArrayList BACKUPArrayList = new ArrayList();
for(int i = 0 ; i <= 5; i++) {
AL.add(i);
BACKUPArrayList = AL;
System.out.println(" ARRAY LIST BEFORE CLEAR " + AL);
AL.clear();
}
System.out.println(" BACK UP LIST AFTER CLEAR" + BACKUPArrayList);
//Unfortunately the BACKUPArrayList is cleaned as well...
}
}
推荐答案
你的备份列表也被清除的原因是在 java 中所有变量都是引用.这意味着 BACKUPArrayList = AL;
行不会将 AL
的内容复制到 BACKUPArrayList
而是使变量(不是对象!)BACKUPArrayList
引用 AL
.所以 AL
和 BACKUPArrayList
在分配之后引用同一个列表.
The reason why your backup list is cleared as well is that in java all variables are references. This means that the line BACKUPArrayList = AL;
doesnt copy the contents of AL
to BACKUPArrayList
but makes the variable (not object!) BACKUPArrayList
references AL
. So both AL
and BACKUPArrayList
reference the same list after that assignment.
要解决这个问题,只需调用BACKUPArrayList.addAll(AL);
.这一行将把 AL
的所有元素添加到 BACKUPArrayList
.另请参阅:http://docs.oracle.com/javase/7/docs/api/java/util/AbstractList.html
To solve this simply call BACKUPArrayList.addAll(AL);
. This line will add all elements of AL
to BACKUPArrayList
. See also: http://docs.oracle.com/javase/7/docs/api/java/util/AbstractList.html
这篇关于调用 .clear() 后,如何在 Java 中备份 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!