Ryan is a Java developer working in software engineering research. His research mainly focuses on source code analysis and development tools. Ryan has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

HashMap vs. TreeMap vs. HashTable vs. LinkedHashMap

03.28.2013
| 74490 views |
  • submit to reddit
Map is an important data structure. In this article, let's play with dogs and see how maps can be helpful in our development.  

1. Map Overview

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 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.
  • This gives us the reason that HashMap should be used if it is thread-safe, since Hashtable has overhead for synchronization. 

2. HashMap 

If key of the HashMap is self-defined objects, then 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 hashMap = new HashMap();
		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 entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());
		}
	}
}
Output:
white dog – 5
black dog – 15
red dog – 10
white 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.  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 == this.color;
	}

	public int hashCode() {
		return color.length();
	}
	
	public String toString(){	
		return color + " dog";
	}
}
Now the output is:
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 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. 

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 == 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 treeMap = new TreeMap();
		treeMap.put(d1, 10);
		treeMap.put(d2, 15);
		treeMap.put(d3, 5);
		treeMap.put(d4, 20);
		
		for (Entry 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{
	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 treeMap = new TreeMap();
		treeMap.put(d1, 10);
		treeMap.put(d2, 15);
		treeMap.put(d3, 5);
		treeMap.put(d4, 20);
		
		for (Entry 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 == 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 linkedHashMap = new LinkedHashMap();
		linkedHashMap.put(d1, 10);
		linkedHashMap.put(d2, 15);
		linkedHashMap.put(d3, 5);
		linkedHashMap.put(d4, 20);
		
		for (Entry 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
Published at DZone with permission of its author, Ryan Wang. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Adrian Buturuga replied on Thu, 2013/03/28 - 5:24am

Hello, 

I've noticed a few problems in the code:

public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}

Comparing strings using == is bad. Consider using equals(). 

Also, what if the passed argument is null? NullPointerException (similar case for hashCode and compareTo)

Casting an argument of a method to a class without check is bad. What if I called dog.equals("test")? ClassCastException

Ryan Wang replied on Thu, 2013/03/28 - 8:24am in response to: Adrian Buturuga

Thanks for pointing those out.

The equals() method checks the actual contents of the string, the "==" operator checks whether the references to the objects are equal. 

In this case "==" operator leads to expected result, because the way how JVM interns string literals. If one of operands is constructed through "new" keyword like new String("something"), "=="  operator will return false.  Therefore, "=="  should be avoided to minimize potential problems. 


String.intern() 

matt inger replied on Thu, 2013/03/28 - 2:59pm

You forgot several.  ConcurrentHashMap, ConcurrentSkipListMap, WeakHashMap, IdentityHashMap to name a few.

Developer Dude replied on Thu, 2013/03/28 - 5:23pm

Using the length of the color string as a hashcode for Dog is not a good idea. You could use a HashCodeBuilder() from Apache.Commons.Lang, or at least use the results of the toString() method, but using the length will result in Black giving you the same hashcode as White as both strings have the same length.

Nor is using a string to define the color - use a Color instead, or an enumeration of allowed colors - the enum defined within the Dog. The string allows me to call the Dog() constructor with null, empty string, or "Bowzer" which is not a color but a name.

Rajesh Mohanan replied on Fri, 2013/03/29 - 1:18am

It would have been better to replace HashTable with ConcurrentHashMap

Raging Infernoz replied on Thu, 2013/04/04 - 3:21am

Both the List (Vector is obsolete!) article and this Map article are full of beginners mistakes e.g. for map equals, it should be:

public boolean equals(Object o) {
  if (o instanceof Dog) {
    String ocol = ((Dog)o).colour;
    return ocol == colour ? true :
           colour == null ? false : 
           colour.equals(ocol);
  }
  return false;
}

See not as simple, because you have to check for the type to avoid ClassCastException and check for nulls!

Ryan Wang replied on Thu, 2013/04/04 - 8:24am in response to: Raging Infernoz

This is trivial. I want the code here to be short. I'm sure you can find other problems if you want do. But the focus is not that. In addition, previous comments have talked about this. 

Thanks for comments anyway. 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.