Difference between HashMap, LinkedHashMap and TreeMap

What is the difference between HashMapLinkedHashMap and TreeMap in Java? I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet()); 
print(m1.values()); 

SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet()); 
print(sm.values());

LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet()); 
print(lm.values());
share edit
 
4 
@gaurav What are you looking for in an answer that isn't already provided here? I'm surprised you shaved off most of your rep to put a bounty on this already well-answered question. –   Paul Bellora  Jul 10 '13 at 20:35
7 
@PaulBellora The reason is in the user's (now deleted) answer: "By mistake I have put a bounty on this question . Please ignore this". –   assylias  Jul 11 '13 at 5:10 
 

8 Answers

up vote 372 down vote accepted

All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:

  • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
  • TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order.
  • LinkedHashMap will iterate in the order in which the entries were put into the map

"Hashtable" is the generic name for hash-based maps. In the context of the Java API, Hashtable is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). UseConcurrrentHashMap instead of Hashtable.

share edit
 
 
What is then Map actually and whats the difference between Map,HashMap and Hashtables. –   Kevin  May 22 '10 at 21:21
2 
@theband: Map is an interface. HashMap and Hashtable both implement it; as I wrote, Hashtable is a legacy class. –   Michael Borgwardt  May 22 '10 at 21:22
 
@theband: Read the API doc, that's what it's for: java.sun.com/javase/6/docs/api/java/util/package-summary.html –   Michael Borgwardt  May 22 '10 at 21:32 
39 
A notable difference between Hashtable and HashMap is that in a Hashtable, "neither the key nor the value can be null". This constraint does not exist on the latter. –   aioobe  May 22 '10 at 21:36
2 
@AshkanN: Yes - in fact those are the standard ways to implement sorting. TreeMap has a constructor that takes a Comparator to use, and if none is provided, it expects all objects added to implement Comparable.–   Michael Borgwardt  Jul 14 '13 at 7:33
up vote 400 down vote
+25

I prefer visual presentation:

╔══════════════╦═════════════════════╦═══════════════════╦══════════════════════╗
║   Property   ║       HashMap       ║      TreeMap      ║     LinkedHashMap    ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║  no guarantee order ║ sorted according  ║                      ║
║   Order      ║ will remain constant║ to the natural    ║    insertion-order   ║
║              ║      over time      ║    ordering       ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║  Get/put     ║                     ║                   ║                      ║
║   remove     ║         O(1)        ║      O(log(n))    ║         O(1)         ║
║ containsKey  ║                     ║                   ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║                     ║   NavigableMap    ║                      ║
║  Interfaces  ║         Map         ║       Map         ║         Map          ║
║              ║                     ║    SortedMap      ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║                     ║                   ║                      ║
║     Null     ║       allowed       ║    only values    ║       allowed        ║
║ values/keys  ║                     ║                   ║                      ║
╠══════════════╬═════════════════════╩═══════════════════╩══════════════════════╣
║              ║   Fail-fast behavior of an iterator cannot be guaranteed       ║
║   Fail-fast  ║ impossible to make any hard guarantees in the presence of      ║
║   behavior   ║           unsynchronized concurrent modification               ║
╠══════════════╬═════════════════════╦═══════════════════╦══════════════════════╣
║              ║                     ║                   ║                      ║
║Implementation║      buckets        ║   Red-Black Tree  ║    double-linked     ║
║              ║                     ║                   ║       buckets        ║
╠══════════════╬═════════════════════╩═══════════════════╩══════════════════════╣
║      Is      ║                                                                ║
║ synchronized ║              implementation is not synchronized                ║
╚══════════════╩════════════════════════════════════════════════════════════════╝
share edit
 
 
Thanks for visual presentation. Can you provide some links for List and Set visual presentation. Thanks again. –   Dhiral Pandya  Nov 21 '13 at 4:30
4 
In addition to insertion-order, LinkedHashMap also supports access-order (when using the constructor with the boolean access-order param). –   Eyal Schneider  Jun 5 '14 at 9:23 
1 
Why this answer is not mark as correct answer? –   Karol Krol  Nov 27 '14 at 14:39
1 
Double Linked Buckets? I think that adds unnecessary overhead of searching for the bucket for insertion/removal operations (because it has to search for the right bucket to put the object in). I always thought that LinkedHashMap implementations would be similar to that of a Map but with a little extra overhead of "entries list" (may be as a linked list) that's used for iteration purposes. Are you sure, shevchyk? If yes, can you explain or give me some online links that back your statement? –   Sai Dubbaka  Dec 8 '14 at 22:42 

All three represent mapping from unique keys to values, and therefore implement the Map interface.

  1. HashMap is a map based on hashing of the keys. It supports O(1) get/put operations. Keys must have consistent implementations of hashCode() and equals() for this to work.

  2. LinkedHashMap is very similar to HashMap, but it adds awareness to the order at which items are added (or accessed), so the iteration order is the same as insertion order (or access order, depending on construction parameters).

  3. TreeMap is a tree based mapping. Its put/get operations take O(log n) time. It requires items to have some comparison mechanism, either with Comparable or Comparator. The iteration order is determined by this mechanism.

share edit
 
1 
So if I understand correctly, the only difference between LinkedHashMap and TreeMap is performance, given that the order of insertion is the same as the natural order? –   Moshe Shaham  Aug 11 '12 at 18:56
12 
@MosheShaham As he said in # 2: LinkedHashMap will iterate in the insertion order, not the natural order. So if you add (2,5,3) to a LinkedHashMap and do a for each over it, it will return 2,5,3. If it were2,5,3 to a TreeMap it will return 2,3,5. –   grinch  Jan 3 '13 at 14:29 
1 
Tree map also has a lot of other nice tricks. Like head and tail maps. –   Thomas Ahle  Jun 5 '14 at 8:49

Just some more input from my own experience with maps, on when I would use each one:

  • HashMap - Most useful when looking for a best-performance (fast) implementation.
  • TreeMap (SortedMap interface) - Most useful when I'm concerned with being able to sort or iterate over the keys in a particular order that I define.
  • LinkedHashMap - Combines advantages of guaranteed ordering from TreeMap without the increased cost of maintaining the TreeMap. (It is almost as fast as the HashMap). In particular, the LinkedHashMap also provides a great starting point for creating a Cache object by overriding the removeEldestEntry() method. This lets you create a Cache object that can expire data using some criteria that you define.
share edit
 
6 
To be precise, TreeMap doesn't keep the elements in order. It keeps the keys in order. –   L S  Apr 25 '13 at 12:40

HashMap

  • It has pair values(keys,values)
  • NO duplication key values
  • unordered unsorted
  • it allows one null key and more than one null values

HashTable

  • same as hash map
  • it does not allows null keys and null values

LinkedHashMap

  • It is ordered version of map implementation
  • Based on linked list and hashing data structures

TreeMap

  • Ordered and sortered version
  • based on hashing data structures
share edit
 

@Amit: SortedMap is an interface whereas TreeMap is a class which implements the SortedMapinterface. That means if follows the protocol which SortedMap asks its implementers to do. A tree unless implemented as search tree, can't give you ordered data because tree can be any kind of tree. So to make TreeMap work like Sorted order, it implements SortedMap ( e.g, Binary Search Tree - BST, balanced BST like AVL and R-B Tree , even Ternary Search Tree - mostly used for iterative searches in ordered way ).

public class TreeMap<K,V>
extends AbstractMap<K,V>
implements SortedMap<K,V>, Cloneable, Serializable

In NUT-SHELL HashMap : gives data in O(1) , no ordering

TreeMap : gives data in O(log N), base 2. with ordered keys

LinkedHashMap : is Hash table with linked list (think of indexed-SkipList) capability to store data in the way it gets inserted in the tree. Best suited to implement LRU ( least recently used ).

share edit
 

These are different implementations of the same interface. Each implementation has some advantages and some disadvantages (fast insert, slow search) or vice versa.

For details look at the javadoc of TreeMapHashMapLinkedHashMap.

share edit
 
 
What are Hashtables actually and what makes it differ from a Map. –   Kevin  May 22 '10 at 21:16

HashMap makes absolutely not guarantees about the iteration order. It can (and will) even change completely when new elements are added. TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order. LinkedHashMap will iterate in the order in which the entries were put into the map

Look at how performance varying.. enter image description here

Tree map which is a implementation of Sorted map takes O(log2n) for put or get due to Natural ordering

Reference: http://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-treemap
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值