What is the best data structure, in java, for getting and setting items by index?
I was initially using ArrayList, but the problem is sometimes, I need to insert an element that is greater than the size of arraylist, like:
array = new ArrayList();
Obviously this returns out an error. I could initialize the array with sentinel values, but using:
will always say that my array is filled to the brim. Obviously it is just filled with sentinel values.
If you always know the index at which you're inserting the value, then using a concrete implementation of the
Map interface is usually the way to go.
The advantage of this set of classes is that, with knowledge of the index (or the
Key in this context), you can directly retrieve the object from memory in O(1) time. That means no searching.
Map<String, String> map = new HashMap<String, String>(); map.put("KEY", "VALUE"); String key = "KEY"; // Do some processing.. String value = map.get(key); // value variable now contains "VALUE".
Have a look at the documentation to get a really solid grasp of how to use this set of classes.
It depends (as so often...). When your indices are within a certain reasonable range and you will use almost all of them, use an array with proper size:
Object items = new Object[MAX_INDEX];
If your range is much larger and many of your array slots will not be used, a
Map (as already stated in other answers) is what you might need.
HashMap is one possible implementation:
Map<Integer, Object> items = new HashMap<Integer, Object>();