简体   繁体   中英

add ArrayList to multiple ArrayList in java

Hi i have problem with ArrayLists i have 3 lists

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

ArrayList1 elements are used for adding values to ArrayList2 for example

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

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

Simply use addAll , and Collections.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 .

This means that every change to list2 will be reflected in each element of list3 .

If this is not the behavior you're expecting, iterate over the length of list1 and add a new ArrayList<Integer>(list2) .

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

is wrong. You must not stop at a < i , it makes no sense! You want to add the whole arrayList2 to ArrayList3, not a number of integers equal to the value of the int i in ArrayList1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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