为什么修改一个数组列表的副本后会更改它 [英] Why does one arraylist change when a copy of it is modified

查看:56
本文介绍了为什么修改一个数组列表的副本后会更改它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它可能很简单,但是仍然让我感到困惑!

Its probably a very simple one but its' still confusing me!

import java.util.ArrayList;

public class Sample {
    ArrayList<Integer> i = new ArrayList<>();
    ArrayList<Integer> j = new ArrayList<>();

    /**
     * @param args
     */
    public static void main(String[] args) {
        new Sample().go();
    }

    private void go() {

        i.add(1);
        i.add(2);
        i.add(3);

        j=i;

        i.remove(0);


        System.out.println(i + "asd" + j);
    }

}

我尝试打印它:

[2, 3]asd[2, 3]

当我改变时,j为什么会改变?原始类型却不会发生!

Why does j change when i changes? Does not happen with primitives though!

推荐答案

语句 j = i; 将引用 j 分配为与相同的引用我.现在, i j 都引用相同的 ArrayList 对象.通过两个引用都可以轻松看到删除第0个索引.

The statement j=i; assigns the reference j to be the same reference as i. Now both i and j refer to the same ArrayList object. The removal of the 0th index is simply visible through both references.

如果您希望删除 i 中的一项不影响 j 中的列表,请创建列表的副本,而不是分配引用:

If you would like the removal of an item in i not to affect the list from j, then create a copy of the list, instead of assigning the references:

j = new ArrayList<Integer>(i);

(这是一个浅表副本,因此列表仍然引用相同的元素.)

(It's a shallow copy, so the lists still refer to the same elements.)

这篇关于为什么修改一个数组列表的副本后会更改它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆