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,这时为什么呢?

解决方案 »

  1.   

    楼上的兄弟好不客气。
    我的意思是克隆后的list应该也是指向之前的集合的,应该会修改容器的对象。
      

  2.   

    不好意思,随便一讲。
    如果一样的话那么他从逻辑上和
    List list1=list;
    区别应该是什么呢?
      

  3.   

    我认为他们没有区别,如果书上没有说错的话,ArrayList list1=(ArrayList)list.clone();
    这一行就包含了你所说的意思
      

  4.   

    clonepublic Object clone()    Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)    Overrides:
            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方法哦
      

  5.   

    来段源码======jdk1.5 for linux src ArrayList.java ln 247=========/**
         * 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();
    }
        }==========================================
      

  6.   

    如果clone实现的功能仅仅是和=等价,那么有何苦重复劳动来设计这么一个东西呢。clone,含义是复制。第七日里面史瓦辛格大叔被clone()了一把,完后他/他们是一个人还是两个人呢?最后直升机上面两个位置可是都坐了人哦