Reputation: 724
I know how to create an ArrayList
of ArrayList
, but how to add new ArrayList
and add value to that particular ArrayList
and how to retrieve the data from that list.
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<ArrayList<Integer>>();
Upvotes: 2
Views: 25578
Reputation: 22972
how to add new ArrayLists and ADD value to that particular ArrayList and how to RETRIEVE the data form that list.
ArrayList<ArrayList<Integer>> arrayList=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> newAL= new ArrayList<Integer>();
arrayList.add(newAL);
newAL.add(1);
newAL.add(2);
newAL.clear();
System.out.println(arrayList.get(0));
//Changes persist in your arraylist
So after adding ArrayList you can manipulate newAL
as ArrayList
stores reference you don't need to fetch and set element from main arrayList
.
To retrive data you can Iterate
(Use ForEach Loop) over arrayList
or you can do following
Integer List0Item1=arrayList.get(0).get(1);//Get first element of list at 0
arrayList.get(0).set(0, 10);//set 0th element of list at 0 as 10
ArrayList<Integer> list10=arrayList.get(10);//get arraylist at position 10
Upvotes: 4
Reputation: 1145
It is a list of list where every object of the parent list is in turn a sublist.The code is something like below:
List<List<String>> mainList = new ArrayList<List<String>>();
List<String> sublist1 = new ArrayList<String>();
sublist1.add("State");
sublist1.add("Country");
sublist1.add("City");
mainList .add(sublist1);
List<String> sublist2 = new ArrayList<String>();
sublist2.add("Sleep");
sublist2.add("Suspend");
sublist2.add("Wait");
mainList .add(sublist2);
for(List<String> obj:mainList){ // iterate
for(String value:obj){
System.out.println(value);
}
}
}
}
Hope this will help to clear your doubt.
Upvotes: 2
Reputation: 35557
You can try this
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
ArrayList<Integer> list1=new ArrayList<>();
ArrayList<Integer> list2=new ArrayList<>();
list1.add(1); // add to list
list1.add(2);
list2.add(3);
list2.add(4);
arrayList.add(list1); // add to list of list
arrayList.add(list2);
for(ArrayList<Integer> i:arrayList){ // iterate -list by list
for(Integer integer:i){ //iterate element by element in a list
}
}
You can get element directly
arrayList.get(0).get(0); // 0th list 0th value
adding value to 0th list
arrayList.get(0).add(1); // 1 will add to 0th index list-list1
Upvotes: 4