Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Both hashed and indexed list or array?

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.

like image 639
Suzan Cioc Avatar asked May 23 '12 09:05

Suzan Cioc


3 Answers

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.

like image 116
Óscar López Avatar answered Nov 06 '22 16:11

Óscar López


You can try LinkedHashSet, I think.

like image 2
Vladimir Ivanov Avatar answered Nov 06 '22 17:11

Vladimir Ivanov


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.

like image 1
Chandra Sekhar Avatar answered Nov 06 '22 17:11

Chandra Sekhar