HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap, hashmaptreemap

Source: Internet
Author: User

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap, hashmaptreemap

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap


Map is one of the most important data structures. In this tutorial, I will show you how to use different maps such as HashMap, TreeMap, HashTable and LinkedHashMap.

Map is a very important type of data structure. In this article, I will show you how to use different maps, such as HashMap, TreeMap, HashTable, and LinkedHashMap.


1. Map


There are 4 commonly used implementations of Map in Java SE-HashMap, TreeMap, Hashtable and LinkedHashMap. If we use one sentence to describe each implementation, it wocould be the following:

  • HashMap is implemented as a hash table, and there is no ordering on keys or values.
  • TreeMap is implemented based on red-black tree structure, and it is ordered by the key.
  • LinkedHashMap preserves the insertion order
  • Hashtable is synchronized, in contrast to HashMap.
  • This gives us the reason that HashMap shoshould be used if it is thread-safe, since Hashtable has overhead for synchronization.

In JavaSE, there are four commonly used Map-HashMap, TreeMap, HashTable and LinkedHashMap.

If we use a separate feature to describe different implementations, it will be listed below:

1) HashMap is implemented as a hash table, and its key and value are unordered.

2) TreeMap is implemented based on the structure of the red/black tree, and its key is ordered.

3) LinkedHashMap ensures the insertion sequence.

4) compared with HashMap, HashTable is synchronous.

Here we give a reason to use HashMap, because HashTable is thread-safe, and its synchronization overhead will be very large.


2. HashMap

If key of the HashMap is self-defined objects, then equals () and hashCode () contract need to be followed.

If we have customized the key object of HashMap, We need to rewrite its equals and hashCode methods as follows:

class Dog {String color; Dog(String c) {color = c;}public String toString(){return color + " dog";}} public class TestHashMap {public static void main(String[] args) {HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();Dog d1 = new Dog("red");Dog d2 = new Dog("black");Dog d3 = new Dog("white");Dog d4 = new Dog("white"); hashMap.put(d1, 10);hashMap.put(d2, 15);hashMap.put(d3, 5);hashMap.put(d4, 20); //print sizeSystem.out.println(hashMap.size()); //loop HashMapfor (Entry<Dog, Integer> entry : hashMap.entrySet()) {System.out.println(entry.getKey().toString() + " - " + entry.getValue());}}}

Output:

4white dog - 5black dog - 15red dog - 10white dog - 20
Note here, we add "white dogs" twice by mistake, but the HashMap takes it. This does not make sense, because now we are confused how many white dogs are really there.

Note that "white dogs" is added twice, but HashMap still obtains it. This obviously makes no sense, because putting a lot of "white dogs" will confuse us.


The Dog class shoshould be defined as follows:

The Dog class should be defined as follows:

class Dog {String color; Dog(String c) {color = c;} public boolean equals(Object o) {return ((Dog) o).color.equals(this.color);} public int hashCode() {return color.length();} public String toString(){return color + " dog";}}

The output is as follows:

3red dog - 10white dog - 20black dog - 15

The reason is that HashMap doesn' t allow two identical elements. by default, the hashCode () and equals () methods implemented in Object class are used. the default hashCode () method gives distinct integers for distinct objects, and the equals () method only returns true when two references refer to the same object. check out the hashCode () and equals () contract if this is not obvious to you.

The reason is that HashMap does not allow two repeated elements. By default, the hashCode and equals methods are implemented when the Object class is used. The default hashCode method will give different integer values to different objects, and the equals method will return true by referring to the references of two identical objects.

If you are not familiar with this topic, read thehashCode () and equals () contract.


Check out the most frequently used methods for HashMap, such as iteration, print, etc.

Read the article mostfrequently used methods for HashMap, including iteration and printing.


3. TreeMap

A TreeMap is sorted by keys. Let's first take a look at the following example to understand the "sorted by keys" idea.

The keys of a TreeMap are ordered. First, let's use the following example to understand the idea of "key sorting.

class Dog {String color; Dog(String c) {color = c;}public boolean equals(Object o) {return ((Dog) o).color.equals(this.color);} public int hashCode() {return color.length();}public String toString(){return color + " dog";}} public class TestTreeMap {public static void main(String[] args) {Dog d1 = new Dog("red");Dog d2 = new Dog("black");Dog d3 = new Dog("white");Dog d4 = new Dog("white"); TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();treeMap.put(d1, 10);treeMap.put(d2, 15);treeMap.put(d3, 5);treeMap.put(d4, 20); for (Entry<Dog, Integer> entry : treeMap.entrySet()) {System.out.println(entry.getKey() + " - " + entry.getValue());}}}

Output:

Exception in thread "main" java.lang.ClassCastException: collection.Dog cannot be cast to java.lang.Comparableat java.util.TreeMap.put(Unknown Source)at collection.TestHashMap.main(TestHashMap.java:35)

Since TreeMaps are sorted by keys, the object for key has to be able to compare with each other, that's why it has to implement Comparable interface. for example, you use String as key, because String implements Comparable interface.

Because TreeMap is key-ordered, its key object can be compared with other objects, which is why it implements the Comparable interface. For example, you use String as the key value because String implements the Comparable interface.


Let's change the Dog, and make it comparable.

Let's change the Dog class so that it can be compared.

class Dog implements Comparable<Dog>{String color;int size; Dog(String c, int s) {color = c;size = s;} public String toString(){return color + " dog";} @Overridepublic int compareTo(Dog o) {return  o.size - this.size;}} public class TestTreeMap {public static void main(String[] args) {Dog d1 = new Dog("red", 30);Dog d2 = new Dog("black", 20);Dog d3 = new Dog("white", 10);Dog d4 = new Dog("white", 10); TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();treeMap.put(d1, 10);treeMap.put(d2, 15);treeMap.put(d3, 5);treeMap.put(d4, 20); for (Entry<Dog, Integer> entry : treeMap.entrySet()) {System.out.println(entry.getKey() + " - " + entry.getValue());}}}


Output:

red dog - 10black dog - 15white dog - 20

It is sorted by key, I. e., dog size in this case.

It is key-ordered, that is, the size of dog.

If "Dog d4 = new Dog (" white ", 10);" is replaced with "Dog d4 = new Dog (" white ", 40);", the output wocould be:

If "Dog d4 = new Dog (" white ", 10);" is replaced with "Dog d4 = newDog (" white ", 40);", the output will be:


white dog - 20red dog - 10black dog - 15white dog - 5

The reason is that TreeMap now uses compareTo () method to compare keys. Different sizes make different dogs!

The result is that TreeMap uses the compareTo method to compare the key value. Different sizes will build different dogs.


4. Hashtable

From Java Doc:
The HashMap class is roughly equivalent to Hashtable, doesn't that it is unsynchronized and permits nulls.

In Java Doc:

The HashMap class is basically the same as HashTable except for non-synchronous and allowed null values.


5. LinkedHashMap

LinkedHashMap is a subclass of HashMap. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order.

LinkedHashMap is a subclass of HashMap. This means that he inherits the features of HashMap. In addition, the chain list ensures the order of inserted elements.


Let's replace the HashMap with your HashMap using the same code used for HashMap.

Let's Replace the HashMap class in the introduced HashMap code with the LinkedHashMap class.

class Dog {String color; Dog(String c) {color = c;} public boolean equals(Object o) {return ((Dog) o).color.equals(this.color);} public int hashCode() {return color.length();} public String toString(){return color + " dog";}} public class TestHashMap {public static void main(String[] args) { Dog d1 = new Dog("red");Dog d2 = new Dog("black");Dog d3 = new Dog("white");Dog d4 = new Dog("white"); LinkedHashMap<Dog, Integer> linkedHashMap = new LinkedHashMap<Dog, Integer>();linkedHashMap.put(d1, 10);linkedHashMap.put(d2, 15);linkedHashMap.put(d3, 5);linkedHashMap.put(d4, 20); for (Entry<Dog, Integer> entry : linkedHashMap.entrySet()) {System.out.println(entry.getKey() + " - " + entry.getValue());}}}

Output:

red dog - 10black dog - 15white dog - 20

The difference is that if we use HashMap the output cocould be the following-the insertion order is not preserved.

The difference is that if we use HashMap for execution, the following format will be output-the insertion order will be disrupted.

red dog - 10white dog - 20black dog - 15


This article Excerpted from http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.