Why doesn't LinkedHashMap provide access by index?

java, linkedhashmap

Solution

a) Because the entries are linked, not randomly accessible. The performance would be miserable, `O(N)` if I'm not in error.

b) Because there is no interface to back up this functionality. So the choice would be to either introduce a dedicated interface just for this (badly performing) Implementation or require clients to program against implementation classes instead of interfaces

Btw with Guava there's a simple solution for you:

Iterables.get(map.values(), offset);

And for caching look at Guava's `MapMaker` and it's expiration features.

Problem

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...

Original source