I have n objects each of them with an identifying number. I get them unsorted but the range of indexes (0, n-1) is used to identify them. I want to access them as fastest as possible. I suppose that an ArrayList would be the best option, I’d add the object with identifier n at the position of the ArrayList with index n by:
list.add(identifier, object);
The problem is that when I am adding the objects I get an IndexOutOfBounds Exception because I’m adding them unsorted and the size() is smaller although I know that previous positions will also be filled.
Another option is to use a HashMap but I suppose that this will decrease performance.
Do you know a collection that has the behavior described above?
It sounds like you need a plain old Java array. And if you need it as a collection, then use “Arrays.asList(…)” to create a
Listwrapper for it.Now this won’t work if you needed to add or remove elements from the array / collection, but it sounds like you don’t need to from your problem description.
If you do need to add / remove elements (as distinct from using
setto update the element at a given position, then Peter Lawrey’s approach is best.By contrast, a
HashMap<Integer, Object>would be an expensive alternative. At a rough estimate, I’d say it that “indexing” operations would be at least 10 times slower, and the data structure would take 10 times the space compared to an equivalent array orArrayListtype. A hash table based solution is only really a viable alternative (from a performance perspective) if the array is large and sparse.