I'm a beginner in Java and I'm trying to create an ArrayList that stores ArrayLists which hold integers. I already know the size I want for the outer ArrayList and want to store the inner ArrayLists. I would then for example want to add all dog ID numbers to the ArrayList stored in the first index of the outer ArrayList, cat ID numbers in the second, and lizard ID numbers in the third.This will happen in a random order so I want the outer ArrayList to have it's size already initialized so I can send an ID number to it's correct inner list when I come across it . This is what I did:
ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>(capacity);
ArrayList<Integer> inner = new ArrayList<Integer>();
for (int i = 0; i < capacity; i++) {
outer.add(null);
}
Would initializing those indices to null increase the size to whatever number is stored in capacity
and allow me to later add a dog to inner by doing outer.get(3).add(10)
and then outer.get(0).add(22)
?
I also thought about doing this:
ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>(capacity);
ArrayList<Integer> inner = new ArrayList<Integer>();
for (int i = 0; i < capacity; i++) {
outer.add(inner);
}
But don't know if adding inner would actually initialize all indices in outer
to Integer ArrayLists or if they would be referencing the "inner" variable itself or something like that.