繁体   English   中英

java arraylist复制的arraylist

[英]java arraylist of arraylist copy

我有如下代码:

    //Assume a has one arrayList in it
    List<List<Integer>> a1 = new ArrayList<List<Integer>>(a);

    for(int i=0;i<1;i++){
        List<Integer> b1 = a1.get(i);
        b1.add(0);
    }

    System.out.println(a.toString()); //now there are 2 elements in arraylist a

我以为上面的代码只能在a1上进行更改。 但是打印结果显示arraylist a1a都被更改。 我如何只更改a1而不a更改。

除了以下内容:

List<List<Integer>> a1 = new ArrayList<List<Integer>>(a);

改为这样做:

a1.addAll(a);

所以有:

List a = new ArrayList();
a.add("Hello");
a.add("World"); 
List a1 = new ArrayList();
a1.addAll(a);
a1.add("GoodBye");
System.out.println(a.toString()); 

我认为在提到“进行更改”时,代码的结构存在一些误解。 下一行:

 List<Integer> b1 = a1.get(i);

换句话说:

"b1 is a List of Integers which is located in memory at the same place as the List of integers located at index i of a1".

因此,b1现在引用a1中索引i处的整数列表(这是基于您的循环的索引0处的列表,它与变量a引用的列表相同)。

当你写:

b1.add(0);

您正在将整数0添加到ab1都引用的整数列表中。 因此,您本质上是在更改a ,并且在此过程中,还更改了a1所持有内容的值。

当您说需要修改a1而不是a时,我不确定您到底需要什么-是否需要向列表中添加新的整数列表? 在这种情况下,您可以简单地执行a1.add(NewList) ,其中NewList是一个List

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM