Reputation: 47
How to store/add list elements in Array-list in the below format?
x.get(0)->[1,2,3,4],
x.get(1)->([5,6,7,8],
x.get(2)->[9,10,11,12],
x.get(3)->[13,14,15,16]
I'm getting a sequence of numbers and want to separate them with a list. When i use x.add(), that is adding all elements to a single list in sequence order.
Upvotes: 0
Views: 979
Reputation: 216
By this way you can add list(ArrayList) into ArrayList
.
//Adding `ArrayList` into `ArrayList`
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> innerList = new ArrayList<Integer>();
//adding element to innerlist
innerList.add(10);
innerList.add(20);
...
//adding innerList into list
list.add(innerList);
if you are getting a sequence of number as : 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16.
Then below code can help you in preparing a list and adding into ArrayList
.
public ArrayList<ArrayList<Integer>> mainlist = new ArrayList<ArrayList<Integer>>();
public void prepareList() {
ArrayList<Integer> innerList = new ArrayList<Integer>();
for (int i = 1; i <= 16; i++) {
innerList.add(i);
if (i % 4 == 0) {
mainlist.add(innerList);
innerList = new ArrayList();
}
}
}
Upvotes: 1
Reputation: 13232
You could do something like this an arraylist of arraylists:
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tempArrayList = new ArrayList<Integer>();
tempArrayList.add(1);
tempArrayList.add(2);
tempArrayList.add(3);
tempArrayList.add(4);
arrayList.add(tempArrayList);
System.out.println(arrayList.get(0).get(0));
System.out.println(arrayList.get(0).get(1));
tempArrayList = new ArrayList<Integer>();
tempArrayList.add(5);
tempArrayList.add(6);
tempArrayList.add(7);
tempArrayList.add(8);
arrayList.add(tempArrayList);
System.out.println(arrayList.get(1).get(0));
System.out.println(arrayList.get(1).get(1));
etc...
If you have a fixed amount of numbers for each list you could do an ArrayList
of int[]
arrays...
Upvotes: 1