I have an Integer ArrayList(mainList) which will have Integer Arrays(subList) inside it, I am trying to add integer array elements to mainList and display them at a later time. Adding subLists to mainList and display all elements from subList.
2 subLists = {1,2,4},{3,2,1}
mainList =[{1,2,4},{3,2,1}]
Display : 1,2,4,3,2,1
- How to easily retrieve elements from mainList
- How to add subLists at a time without looping
The following is the way I am trying to add subLists to mainList
//Adding elements
ArrayList<ArrayList<Integer>> mainList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> subList = new ArrayList<Integer>();
for(int i=0;i<10;i++) {
for(int j=i+1;j<10;j++){
//Do something and add elements to subList
subList.add(element[j]) }
mainList.add(subList);
// When I clear subList mainList is also getting cleared. I want to add the elements of subList to mainList. I was able to do it with loops but how to do this way
subList.clear();
}
//Printing, How do I get the elements from mainList which will have subLists
for(Integer i:mainList){
System.out.println(i);
}
}
ArrayList<Integer><ArrayList<Integer>> mainList = new ArrayList<ArrayList<Integer>>(); how did this compile?ArrayList<Integer><ArrayList<Integer>>is not compilable. You'd do better to useListas the declared type:List<List<Integer>> mainList = new ArrayList<>();. Likewisefor(Integer i:mainList)is not compilable (and should have one blank on either side of the:) because the element type ofmainListis notInteger. You can only get the element type of theListyou're iterating. You will need to nest asubListloop inside yourmainListloop. Names should reflect the domain, not the implementation.