Alex Rivera | Logout

Why doesn't LinkedHashMap provide access by index?

Asked 2011-04-14T16:59:55.820
12

From Javadoc:
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.

If it is so, then why doesn't it provide object access like List in java, list.get(index);

UPDATE

I had implemented LRU Cache using LinkedHashMap. My algorithm required me to access LRU Object from the cache. That's why I required random access, but I think that will cost me bad performance, so I have changed the logic and I am accessing the LRU object just when Cache is full...using removeEldestEntry()

Thank you all...

Edit
Report

2 Answers

1

It provides an Iterator interface, each node in the list is linked to the one before it and after it. Having a get(i) method would be no different than iterating over all the elements in the list since there is no backing array (same as LinkedList).

If you require this ability which isn't very performant I suggest extending the map yourself

answered 2011-04-14T17:06:00.550
1

If you want random access you can do

Map<K,V> map = new LinkedHashMap<K,V>();
Map.Entry<K,V>[] entries = (Map.Entry<K,V>[]) map.toArray(new Map.Entry[map.size()]);
Map.Entry<K,V> entry_n = entry[n];

As you can see the performance is likely to be very poor unless you cache the entries array.

I would question the need for it however.

answered 2011-04-14T17:22:04.527

Your Answer