Skip to content

Instantly share code, notes, and snippets.

@panthole
Created August 10, 2016 08:31
Show Gist options
  • Save panthole/50ab224114bb2aec558373a3bff99041 to your computer and use it in GitHub Desktop.
Save panthole/50ab224114bb2aec558373a3bff99041 to your computer and use it in GitHub Desktop.
ArrayList<Object>深浅拷贝分析
例如我有一个ArrayList里面包含3个int[]数组
int [] arr1 = new int [10];
int [] arr2 = new int [10];
int [] arr2 = new int [10];
ArrayList al = new Arraylist();
al.add(arr1);
al.add(arr2);
al.add(arr3);
此时,你要如何才能把al这个ArrayList拷贝给al2?
ArrayList al2 = new ArrayList(al); // 这个是引用
ArrayList al2; al2=al; //这个也是引用
ArrayList al2 = new ArrayList();
for(Object obj: al){
al2.add( (int[])obj);
}//这个是引用,你要是对al2的成员进行修改,会影响到al
例如:
al2.get(0)[0]=8;
这个操作之后,al以及al2的第一个对象的第一个成员都会变成8;
ArrayList al2 = new ArrayList();
for(Object obj: al){
al2.add( ((int[])obj).clone() );
} //这个是深拷贝
还有一个问题,就是浅拷贝的问题
例如你的 ArrayList al里面有数组还有数字:
第一个object: 3
第二个object: [1,2,3]
第三个object: 4
这种情况下,你直接
for(Object obj: al){
al2.add( (int[])obj);
}
的话,al2的结构就是这样的:
第一个object: 3
第二个object: 一个指向[1,2,3]数组的引用
第三个object: 4
@panthole
Copy link
Author

ArrayList.addAll()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment