简体   繁体   中英

Accessing Arraylist of Arraylist<ArrayList>

I have an arraylist of an arraylist declared like

ArrayList<ArrayList<Integer>> bigList = new ArrayList<ArrayList<Integer>>();

I would then add to this bigList by bigList.add(arraylist) . I then have a class that takes ArrayList<Integer> as a construcor parameter. My question is how do I send a certain ArrayList in bigList to this class as a constructor parameter? I can iterate through my bigList with

for(ArrayList<Integer> list : bigList) {
    for(Integer num : list)
        System.out.println(num);
}

but I have not been able to send a whole ArrayList element to another class. Thanks a bunch.

You can select an ArrayList at a particular index and pass it to a constructor as follows:

int index = 2; // the index of the list you want to pass to the constructor
MyNewObject newObject = new MyNewObject(bigList.get(index));

Have you tried:

List<SomeClass> sList = new ArrayList<>();

for(ArrayList<Integer> list : bigList) {
  sList.add(new SomeClass(list));
}

This would work fine if you are looking to iterate though all lists in bigList and construct new instances from all of them. Alternatively, if you just want to create one such object for a specific list at index "i" of bigList:

SomeClass s = new SomeClass(bigList.get(i));

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