1

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.

Alex
  • 63
  • 5
  • Understand that `ArrayList` is dynamic and it will change it's size as required. The `initialCapacity` property is a guide which allows the `ArrayList` to initialise itself to a "initial" state and can also act as a guide to how large it's "resize" can be - this helps improve performance. Can you check this by inspecting the `size` property of the `ArrayList`, which will be `0` when it's first initialised, as there is nothing in it – MadProgrammer Mar 19 '18 at 02:54
  • Beware of this: [Why does my ArrayList contain N copies of the last item added to the list?](https://stackoverflow.com/q/19843506/5221149) – Andreas Mar 19 '18 at 02:57

1 Answers1

3

ArrayList has size (the number of elements) and capacity (the number of elements it can hold before it needs to automatically expand) which can be used for optimization, for now you can safely ignore capacity and just add and remove elements based on your needs.

Create the outer array with:

ArrayList<ArrayList<Integer>> outer = new ArrayList<>();

And then add all the inner arrays you need:

for (int i = 0; i < capacity; i++) {
    outer.add(new ArrayList<Integer>());
}   
Oleg
  • 6,124
  • 2
  • 23
  • 40