--
A LinkedHashMap
differs from HashMap
in that the order of elements is maintained. - A
HashMap
has a better performance than aLinkedHashMap
because aLinkedHashMap
needs the expense of maintaining the linked list. TheLinkedHashMap
implements a normal hashtable, but with the added benefit of the keys of the hashtable being stored as a doubly-linked list. - Both of their methods are not synchronized.
Let's take a look their API documentations:
The HashMap is a hash table with buckets in each hash slot. Like in the API documentation:
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
The LinkedHashMap is a linked list implementing the map interface. As said in the API documentation:
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. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
No! A LinkedHashMap is not a linked list implementing the map interface. It's a hash table and a linked list. But then again, this is just blogspam, so why am I answering it...
ReplyDeleteOne of the reasons I use LinkedHashMap is its deterministic insertion order. If you debugging code with 10s or 100s of entries and you want to look at the last N added entries, this is obvious (as they appear last)
ReplyDeleteHowever for HashMap they are added in a pseudo random making checking your result more difficult.
Another use for LHM which is often forgotten is its use as a simple fixed size LRU cache.