简体   繁体   English

将ArrayList的项目添加到ArrayList的其他ArrayList

[英]Adding items of ArrayList to other ArrayList of ArrayList

I have added an item to list a and then added list a to list b and did the same thing again. 我将一个项目添加到列表a ,然后将列表a添加到列表b ,然后再次执行相同的操作。

My question is if I print b.get(0) and b.get(1) , I am getting the same list that is both the items "One" and "Two" , why is it so? 我的问题是,如果我打印b.get(0)b.get(1) ,得到的列表都是"One""Two" ,为什么会这样?

At b.get(0) I want to get only one item I added that is a.add("One") . b.get(0)我只想添加一个项,即a.add("One")

After adding a.add("Two") , if I print b.get(1) I should get both "One" and "Two" ? 添加a.add("Two") ,如果我打印b.get(1)我应该同时获得"One""Two"吗?

Is there any solution or any changes to manage this? 是否有解决方案或任何更改来管理?

List<String> a= new ArrayList<String>();
List<List<String>> b= new ArrayList<List<String>>();

a.add("One");
b.add(a);

a.add("Two");
b.add(a);

System.out.println("b="+b.get(0));
System.out.println("b="+b.get(1));

output: 输出:

b=[One, Two]
b=[One, Two]

You are adding the same List twice, so you see the same elements for both indices of the outer List. 您将两次添加相同的List,因此对于外部List的两个索引,您将看到相同的元素。

In order to add two different List s, you must create a new ArrayList before adding each element to the outer List : 为了添加两个不同的List ,必须在将每个元素添加到外部List之前创建一个新的ArrayList

a.add("One");
b.add(a);

a = new ArrayList<>(a); // assuming you want the second list to contain both "One" and "Two"
a.add("Two");
b.add(a);

You are adding the same reference in b[0] and b[1]. 您要在b [0]和b [1]中添加相同的引用。 If you want to have differente lists at diferent index on list b you have to create a new List object 如果要在列表b的不同索引处具有不同的列表,则必须创建一个新的List对象

        List<String> a= new ArrayList<String>();
    List<String> c= new ArrayList<String>();
    List<List<String>> b= new ArrayList<List<String>>();
    a.add("One");
    b.add(a);

    c= new ArrayList<String>();
    c.addAll(a);
    c.add("Two");
    b.add(c);

    System.out.println("b="+b.get(0));
    System.out.println("b="+b.get(1));

the reason is in your code, the b.get(0) and b.get(1) point to the same List a, so the output is same. 原因是在您的代码中,b.get(0)和b.get(1)指向相同的列表a,因此输出相同。

use this code can achieve what you want, List a1= new ArrayList(); 使用此代码可以实现您想要的,List a1 = new ArrayList(); List a2= new ArrayList(); 列出a2 = new ArrayList(); List> b= new ArrayList>(); List> b = new ArrayList>();

    a1.add("One");
    b.add(a1);

    a2.add("Two");
    b.add(a2);

    System.out.println("b="+b.get(0));
    System.out.println("b="+b.get(1));

output is, b=[One] 100 b=[Two] 输出是b = [一个] 100 b = [两个]

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

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