HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

Map is one of the most important data structures in Java. In this post, I will illustrate how to use different types of maps, such as HashMap, TreeMap, HashTable and LinkedHashMap.

1. Map Overview

There are 4 commonly used implementations of Map in Java SE – HashMap, TreeMap, Hashtable and LinkedHashMap. If we use only one sentence to describe each implementation, it would 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. It has an overhead for synchronization.
  • This is the reason that HashMap should be used if the program is thread-safe.

2. HashMap

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

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 size
		System.out.println(hashMap.size());
 
		//loop HashMap
		for (Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());
		}
	}
}

Output:

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

Note here, we add “white dogs” twice by mistake, but the HashMap accepts it. This does not make sense, because now we are confused with how many white dogs are really there.

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";
	}
}

Now the output is:

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

The reason is that HashMap doesn’t allow two identical elements. By default, the hashCode() and equals() methods implemented in the 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.

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

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.

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.Comparable
	at 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.

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

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 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 - 10
black dog - 15
white dog - 20

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

If “Dog d4 = new Dog(“white”, 10);” is replaced with “Dog d4 = new Dog(“white”, 40);”, the output would be:

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

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

4. Hashtable

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

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.

Let’s replace the HashMap with LinkedHashMap using the same code used for HashMap.

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 is:

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

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

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

Read: ArrayList vs. LinkedList vs. Vector

23 thoughts on “HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap”

  1. Note that with a TreeMap it is strongly recommended that the compareTo implementation be consistent with equals. If for example the comparator used only compares some members (like size in your case) then two dogs with the same size but different colour would be treated as equal.

    This is a common mistake where some will think the Comparator implementation only represents the sort order, but it’s important for equality in this case.

    It’s also important that your equals and compareTo implementations are consistent to obey the contract given in the Map interface.

    Another point I would like to add is that with all keys for any implementation it’s advised that they are immutable. If mutation should occur after the insertion of a key then the map has been compromised. Making your member variables final will satisfy this contract. It’s permissible that members not deeming equality can be mutable, however it is ill advised unless transient.

  2. Your Dog.equals() and Dog.hashCode() methods are CRAP.

    The equals method uses == to compare two Strings. If you need to check that two Strings are the same, use String.equals(), not ==. The == operator checks if the two objects have the same memory address, that is, if they are in fact the same object, as opposed to two identical objects. The ONLY reason you example works is because Java only creates one instance of each hardcoded String in the source when the program starts up.

    The equals method also does not check to make sure the object being compared to is a Dog object. If a Cat is passed in, you will get an exception for casting a Cat as a Dog.

    The hashCode method is not robust in the slightest. Instead of returning the string’s length, which has a high probability of repeating and clusters in the range of 1-10, you should at least do something like “return color.hashCode()” and take advantage of String’s robust hashCode method.

    The point of a hashCode method is to generate a reproducible value based on the object’s attributes, such that any two objects which are o1.equals(o2) == true will produce the same hash, but any two objects which are not equal are unlikely to produce the same hash. The hashes should be fairly evenly distributed between Integer.MAX_VALUE and Integer.MIN_VALUE, or at least 0 and Integer.MAX_VALUE. If you don’t know how to generate a good hash algorithm, then just leverage String’s hashCode() function on whatever String or combination of Strings is most likely to be unique between two different objects of that type.

  3. There is concurrentHashMap but which was added a while back. That being said I believe only one thread at a time can alter a concurrent hash map and it is still not as predictable as HashTable.

  4. Also, HashMap is better solution if you are only using a single thread and is more scalable. Not sure if that is to much detail for this brief summary though.

  5. Hashtable class methods all are Synchronized.

    HashMap class methods are not Synchronized.

    for example you created a method with Synchronized, in that you wrote some code using HashMap Or you added some elements to HashMap and displaying using keys in that method. So no two threads cannot access the method at a time. if the same method is not Synchronized, multiple threads can access the method then HashMap code will be broken.

    if you use HashTable instead of HashMap in non synchronized method the code wont break bcoz HashTable already have synchronized methods they wont allow two threads to access.

    thread safe means only one thread can allow.

    putting HashTable inside thread safe method is no use, so put HashMap inside thread safe

    pleas correct me if it is wrong.

  6. Because 40 is weight inside the key, by which key-value pairs are sorted (due to overriden compareTo method). 5 in the output is the value , that is extracted by entry.getValue().
    To simplify , here how looks element of treeMap here [ KEY : DogObject(FieldColor=white, fieldSize=40) : VALUE: 5 ]
    Code takes KEY that is DogObject, compareTo takes fieldSize and compare with others same fieldSizes in other DogObjects that already present in KEYs, then place key-pair DogObject : 5 to some pleace of the map , depending of is 40 is big or not.

  7. Awesome explanation .. really cleared my doubts. Thank for the great post.

    I had one doubt though..For tree map;

    If “Dog d4 = new Dog(“white”, 10);” is replaced with “Dog d4 = new Dog(“white”, 40);”, the output would be:

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

    Why will the output for white dog not be 40 ? and why is output as 5 ?

  8. HI, Hashtable is thread safe , but you mentioned as below, hashmap is thread safe please correct it…

    “This gives us the reason that HashMap should be used if it is thread-safe, since Hashtable has overhead for synchronization.”

Leave a Comment