views:

355

answers:

4

If LinkedHashMap's time complexity is same as HashMap's complexity why do we need HashMap? What are all the extra overhead LinkedHashMap has when compared to HashMap in Java?

+7  A: 

LinkedHashMap will take more memory. Each entry in a normal HashMap just has the key and the value. Each LinkedHashMap entry has those references and references to the next and previous entries. There's also a little bit more housekeeping to do, although that's usually irrelevant.

Jon Skeet
As a result, the performance is slightly lower compared to that of HashMap.
Snehal
@Jon Skeet Is it like values in case of LinkedHashMap consist of extra references to previous and next value, deletion or insertion of any item would take extra cost for reconnecting as well? It would be great if I get complete implementation either has a link or explained.
Passionate programmer
@Passionate programmer: The source code is publicly available - why not look there? And yes, insertion and deletion does require the linked list to be updated.
Jon Skeet
@I am not a Java programmer and I don't know where it can be found :(.
Passionate programmer
@Passionate programmer: See http://download.java.net/jdk6/source/
Jon Skeet
@Jon Skeet Thanks for helping out, I don't think I have the source code in that URL, should I log in??
Passionate programmer
@Passionate programmer If you've already downloaded a JDK the sources are included in JAVA_HOME\src.zip
stacker
+7  A: 
  • LinkedHashMap additionally maintains a doubly-linked list running through all of its entries, that will provide a reproducable order. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
  • HashMap doesn't have these extra costs (runtime,space) and should prefered over LinkedHashMap when you don't care about insertion order.
stacker
+1  A: 

LinkedHashMap is useful datastructure when you need to know the insertion order to the Map. One suitable use case is for the implementation of an LRU cache. Due to order maintainence of the LinkedHashMap, the performance of the datastructure is slightly lower compared to that of a randomized Map such as HashMap. In case you do not need to know the insertion order, you should always go for the HashMap for better performance.

Snehal
+4  A: 

If LinkedHashMap's time complexity is same as HashMap's complexity why do we need HashMap?

You should not confuse complexity with performance. Two algorithms can have the same complexity, yet one can consistently perform better than the other.

Remember that f(N) is O(N) means that:

C1*N <= limit(f(N), N -> infinity) <= C2*N  

where C1 and C2 are strictly positive constants. The complexity says nothing about how small or large the C values are.

Stephen C