import java.util.*;public class TestClone
{
public static void main(String[] args){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<5;i++)list.add(i);
ArrayList list1=(ArrayList)list.clone();
list1.remove(2);
System.out.println(list);
System.out.println(list1==list);
}
}
打印的是【1,2,3,4】,还有就是false,这时为什么呢?
{
public static void main(String[] args){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<5;i++)list.add(i);
ArrayList list1=(ArrayList)list.clone();
list1.remove(2);
System.out.println(list);
System.out.println(list1==list);
}
}
打印的是【1,2,3,4】,还有就是false,这时为什么呢?
我的意思是克隆后的list应该也是指向之前的集合的,应该会修改容器的对象。
如果一样的话那么他从逻辑上和
List list1=list;
区别应该是什么呢?
这一行就包含了你所说的意思
clone in class Object Returns:
a clone of this ArrayList instance.
See Also:
Cloneable========================
看了一下API,明白LZ说的意思了
(The elements themselves are not copied.)
应该是说这句话吧。看看下面的能不能说清楚。Object a=new Object();
Object b=a;
a=null;
assert(b==null); // ??????=======
在list中remove(2)了,但是list2是包含另一个指针(引用),指向相同的地方,
所以elementAt(2)还是好好的,gc不管他的
至于这个false那就比较简单了,== 和 equals() 的区别应该还是可以区分的。
对于对象前者比较地址,后者比较值。原始类型没有equals方法哦
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance.
*/
public Object clone() {
try {
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = (E[])new Object[size];
System.arraycopy(elementData, 0, v.elementData, 0, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}==========================================