Tuesday, February 14, 2012

Java: Best way to store to an arbitrary index of an ArrayList

I know that I cannot store a value at an index of an ArrayList that hasn't been used yet, i.e. is less than the size. In other words, if myArrayList.size() is 5, then if I try to do

myArrayList.set(10, "Hello World")

I will get an out of bounds error. But my app needs this. Other than a loop of storing null in each of the intermediate slots, is there a more elegant way?

It looks to me like:

  • This behavior is the same in Vector

  • If I need to be able to randomly access (i.e. element at pos X) then my choices are Vector and ArrayList.

  • I could use a HashMap and use the index as a key but that's really inefficient.

So what is the elegant solution to what looks like a common case. I must be missing something...


  1. I could use a HashMap and use the index as a key but that's really inefficient.

    Depends. If the indices you use are very sparse, it might be a lot better to use a Map. If the indices tend to be closely together, I think there is no better way than to fill it with nulls. Just write a utility function for it that you can use over and over instead of repeating the loop everywhere you need it, something like this:

    private void padTo(List<?> list, int size) {
    for (int i=list.size(); i<size; i++)

  2. You can use a Map<Integer, MyClass> instead. Specifically, if you use HashMap, it will also be O(1) - though it will be slower than ArrayList.

  3. Sounds like you want a regular array:

    You want random access
    You want to specify some large size

  4. If you definitely have to use the list and not a map, then it's best you override the arraylist's add and set methods to first put a null in indexes before. No other better way IMO

  5. HashMap is probably much less inefficient than you think, try it. Otherwise, I can think of no way of doing it more elegantly than looping and filling with null. If you want elegance of exposition at least, then you could always subclass ArrayList and add an expandingSet(position, value) method to hide all the looping and such, or something. Perhaps this isn't an option though? If not just have a utility method somewhere else for it, but this is not as nice imho, though it will work also with other types of list too I guess...

    Perhaps a wrapper class would be the best of both worlds, or perhaps it would just incur unnecessary overhead...

  6. You can use TreeMap<key, value>, which is sorted in natural order by the value.

    Here you can keep value as the index. You can insert any value, it need not be in order. This seems the simplest solution.

  7. If you are looking for a sparse array (where most of the indices will be empty), a Map of some sort (probably a HashMap) will be your best bet. Any array-esque solution will be forced to reserve space for all the empty indices, which is not very space-efficient, and a HashMap is fast enough for most normal purposes.

    If you will eventually fill up the array up to some n, you will need to add nulls in a loop to get to the index you want. You can make this somewhat more efficient by giving it an initial capacity of the number of elements you will eventually want to store (this prevents the ArrayList from needing to resize itself). new ArrayList(n) will work fine. Unfortunately, there is no simple way of making it a certain size to begin with except adding things in a loop when you make it.