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.
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.
You can try LinkedHashSet, I think.
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.
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