ArrayList的copy()方法

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);
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值