[Simple Java] HashMap vs TreeMap vs Hashtable vs LinkedHashMap, hashmaptreemap

Source: Internet
Author: User

[Simple Java] HashMap vs TreeMap vs Hashtable vs LinkedHashMap, hashmaptreemap

Map is an important data structure. This article describes how to use different maps, such as HashMap, TreeMap, HashTable, and LinkedHashMap.

Map Overview

 

Java has four common Map implementations: HashMap, TreeMap, HashTable, and LinkedHashMap. We can describe each Map in one sentence, as shown below:

  • HashMap: unordered implementation based on the hash;
  • TreeMap: implemented based on the red/black tree and sorted by Key;
  • LinkedHashMap: stores the insertion sequence;
  • Hashtable: synchronous, similar to HashMap;
HashMap

If the Key of HashMap is a defined object, it is generally necessary to overwrite the equals () and hashCode () methods and follow the conventions between them.

package simplejava;import java.util.HashMap;import java.util.Map.Entry;class Dog {    String color;    Dog(String c) {        color = c;    }    public String toString() {        return color + " dog";    }}public class Q26 {    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 size        System.out.println(hashMap.size());        //loop HashMap        for (Entry<Dog, Integer> entry : hashMap.entrySet()) {        System.out.println(entry.getKey().toString() + " - " +        entry.getValue());        }    }}

Result output:

4
White dog-5
Red dog-10
White dog-20
Black dog-15

Note that we accidentally added two "white dogs", but HashMap still stores it. This is unreasonable. Now we are confused about how many white dogs have stored in HashMap, 5 or 20.

In fact, 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";    }}

Result output:

3
Red dog-10
White dog-20
Black dog-15

The reason is that HashMap does not allow two identical elements to be stored. By default, the hashCode () and equals () of the Object are used to determine whether the two objects are the same. The default hashCode () method returns different values for different objects, while the equals () method returns true only when two references are equal, that is, pointing to the same object. If you are not very clear, you can test the relationship between hashCode () and equals () by yourself.

For example, we can check the most common methods in HashMap, such as iteration and print.

TreeMap

TreeMap is sorted by key. Let's take a look at the following code to understand its "sort by key" idea.

package simplejava;import java.util.Map.Entry;import java.util.TreeMap;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 Q26 {    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());        }    }}

Result output:

Exception in thread "main" java. lang. ClassCastException: simplejava. Dog cannot be cast to java. lang. Comparable
At java. util. TreeMap. compare (TreeMap. java: 1188)
At java. util. TreeMap. put (TreeMap. java: 531)
At simplejava. Q26.main (Q26.java: 34)

Because TreeSet is based on Key sorting, the objects as keys need to be compared with each other, which is why keys need to implement the Comparable interface. For example, you can use a String as the Key, because String has implemented the Comparable interface.

Now let's change the Dog to make it comparable, as shown below:

package simplejava;import java.util.Map.Entry;import java.util.TreeMap;class Dog implements Comparable<Dog> {    String color;    int size;    Dog(String c, int s) {        color = c;        size = s;    }    public String toString() {        return color + " dog";    }    @Override    public int compareTo(Dog o) {        return o.size - this.size;    }}public class Q26 {    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());        }    }}

Result printing:

Red dog-10
Black dog-15
White dog-20

In this example, we sort by dog size;

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

White dog-20
Red dog-10
Black dog-15
White dog-5


This is because the current TreeMap uses compareTo () to compare keys. Different Sizes mean different dogs.

HashTable

Refer to the java document: HashMap and HashTable are similar, except for non-synchronous and allowed null.

LinkedHashMap

LinkedHashMap is a subclass of HashMap, meaning it inherits the features of HashMap. In addition, LinkedHashMap also saves the insertion sequence.

Let's use the same code and replace HashMap with LinkedHashMap, as shown below:

package simplejava;import java.util.LinkedHashMap;import java.util.Map.Entry;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 Q26 {    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 result:

Red dog-10
Black dog-15
White dog-20

If we use HashMap, the result is as follows. The difference is that the insertion sequence is not saved:

Red dog-10
White dog-20
Black dog-15

 

For more information, see ArrayList vs. Alibaba list vs. Vector.

Http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/.

 

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.