Reputation: 7
I have got a loop with 2d list where I delete and add elements and want to add those temporary arraylists to the dimensions of another list.
Example,
// 2d list
List<List<Integer>> p = new ArrayList<List<Integer>>();
// 3d list
List<List<List<List<Integer>>>> list1 = new ArrayList<List<List<List<Integer>>>>();
// this compiles ok
list1.get(0).add(p);
but I get the following error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Upvotes: 0
Views: 197
Reputation: 1037
You need to instantiate every list.. not just the one you are trying to access. Meaning that if you have a 2x2 matrix, you need 2 rows = 2 lists, and another list to hold them both, and so on if the matrix starts getting more complex.
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
List<Integer> row = new ArrayList<Integer>();
matrix.add(row);
Upvotes: 1
Reputation: 7714
Your "list1" object is actually 4d in your example, but those are not initialized, so when you ask "list1" to get the first (three dimensional) list inside, it does not exist at all (arrays in Java starts at 0 size), so there is nothing to add there.
You could do something like:
List<List<List<List<Integer>>>> list1 = new ArrayList<List<List<List<Integer>>>>();
List<List<List<Integer>>>> 3dlist = new ArrayList<List<List<Integer>>>();
list1.add(3dlist)
list1.get(0).add(p);
Now, using multidimensionnal arrays directly like this is not really practical - you may want to encapsulate them in an object.
Upvotes: 0