Alex
Alex

Reputation: 63

ArrayList of ArrayLists, default values

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.

Upvotes: 1

Views: 1129

Answers (1)

Oleg
Oleg

Reputation: 6314

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>());
}   

Upvotes: 3

Related Questions