If you are looking for a sparse array (where most of the indices will be empty), then it is best to use a map of some kind (possibly a HashMap). Any array-esk solution will be forced to reserve space for all empty indexes, which is not very efficient in terms of space, and HashMap is fast enough for most common purposes.
If you end up filling the array with some n, you will need to add zeros in the loop to get the index you need. You can make this somewhat more efficient by providing it with the initial capacity of the number of elements that you ultimately want to save (this prevents the ArrayList from resizing). new ArrayList(n) will work fine. Unfortunately, there is no easy way to make it a specific size to start with, other than adding things to the loop when you do it.
source share