简体   繁体   English

在Java中将ArrayList添加到多个ArrayList

[英]add ArrayList to multiple ArrayList in java

Hi i have problem with ArrayLists i have 3 lists 嗨,我有ArrayLists的问题,我有3个列表

ArrayList1<Integer>=[1,2,3]
ArrayList2<Integer>=[]
ArrayList3<ArrayList<Integer>>=[]

ArrayList1 elements are used for adding values to ArrayList2 for example ArrayList1元素用于向ArrayList2添加值

for(int i:ArrayList1)
{
  for(int a=0;a<i;a++)
  {
    ArrayList2.add(a);
  }

}

and that works fine no problem there but now i want to for every element in ArrayList1 to add ArrayList2 to ArrayList3 this is what I have come up with but it does not work 并且工作正常,没有问题,但是现在我想为ArrayList1中的每个元素添加ArrayList2到ArrayList3,这是我想出的,但它不起作用

 for(int i:ArrayList1)
    {
      for(int a=0;a<i;a++)
      {
        ArrayList2.add(a);
      }
      ArrayList3.add(ArrayList2);
    }

Simply use addAll , and Collections.fill . 只需使用addAllCollections.fill

Example

list2.addAll(list1);
list3 = new ArrayList<ArrayList<Integer>>(list1.size());
Collections.fill(list3, list2);

Note that list3 will be filled with the same instance of list2 . 请注意, list3将使用相同list2实例填充。

This means that every change to list2 will be reflected in each element of list3 . 这意味着对list2每次更改都会反映在list3每个元素中。

If this is not the behavior you're expecting, iterate over the length of list1 and add a new ArrayList<Integer>(list2) . 如果这不是您期望的行为,请遍历list1的长度并添加一个new ArrayList<Integer>(list2)

for(int a=0;a<i;a++)

is wrong. 是错的。 You must not stop at a < i , it makes no sense! 您一定不要在a < i处停下来,这没有任何意义! You want to add the whole arrayList2 to ArrayList3, not a number of integers equal to the value of the int i in ArrayList1. 您想将整个arrayList2添加到ArrayList3,而不是等于ArrayList1中int i值的整数。

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

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