Reputation: 30097
Is there any class in Java, which holds an array of elements both in order and optimized for fast searching?
I.e. I need to retrieve elements both by numeric index (like in Vector
) and by hash (like in HashMap
).
LinkedHashMap does not match
I think LinkedHashMap
does not match since it guarantees order, but does not allow fast accessing by index (position number). According to description, it will require to traverse entire chain to find a given position. This is what any Collection
can with iterator.
EDIT 2
I.e. both searching by key and by index should be fast, not only by key.
Upvotes: 5
Views: 150
Reputation: 235984
You can use a Map
for fast retrieval of elements by hash. By definition, a Map
is unordered and talking about indexes doesn't make much sense. Using a LinkedHashMap might be of use, since it guarantees that insertion order is preserved at iteration time, although accessing an element by index will still need some extra processing, something like this:
map.entrySet().toArray()[index] // mind the casts, etc.
If your map changes infrequently, the above will work nicely if you cache the array and check to see if the size of the map has changed before accessing an entry by index, creating a new array only when a change in size has been detected. On the other hand, if the map changes frequently you'd need to re-create the array at each access, creating a poorly performing data structure.
Upvotes: 2
Reputation: 10121
I think you're looking for LinkedHashMap
From the docs:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
Upvotes: 1
Reputation: 19492
use LinkedHashMap. This will let you retrieve the elements through key. And also you can retrieve the elements in the same sequence as you stored in it.
Upvotes: 1