Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 687
pitosalas Avatar asked Feb 10 '12 16:02

pitosalas


People also ask

How do you add data to an ArrayList at a specific index?

add() method is used to add an element at particular index in Java ArrayList.

Can you index an ArrayList Java?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int.

How do you access an index from an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().


2 Answers

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++)
        list.add(null);
}
like image 174
Steven Avatar answered Sep 21 '22 05:09

Steven


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.

like image 45
Bhushan Avatar answered Sep 21 '22 05:09

Bhushan