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:
So what is the elegant solution to what looks like a common case. I must be missing something...
add() method is used to add an element at particular index in Java ArrayList.
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.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With