public class Info {
public static void main(String[] args) {
ArrayList<A> list = new ArrayList<>();
list.add(new A(1));
ArrayList<A> copy = (ArrayList<A>) list.clone();
copy.add(new A(2));
printList(copy);
printList(list);
//修改了第一个插入元素里面的值
list.get(0).a = 3;
printList(copy);
printList(list);
}
public static void printList(List list) {
list.stream().forEach(e -> System.out.print(e));
System.out.println();
}
}
class A {
public int a;
public A(int a) {
this.a = a;
}
@Override
public String toString() {
return a + " ";
}
}
程序的结果:
1 2
1
3 2
3
原因是ArrayList的copy方法时浅拷贝。copy出来的list都是新的数组,但是list里存的数据里的值是没有改变的。
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* 返回一个当前实例的浅拷贝。(list中的元素没有进行拷贝)。
* 如果对list中的某个元素里的内容进行修改,对这两个实例都会有影响。
* 这里也做不到深拷贝,除非list存储的元素都实现了copy方法,并且也都是深拷贝。
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}