HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

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是数据结构中非常重要的一种。在该文章中,我将会告诉你如何去使用不同的map,诸如HashMap,TreeMap,HashTable和LinkedHashMap。


1.   Map

vs


        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.

  在JavaSE中有常用的四种Map – HashMap,TreeMap,HashTable和LinkedHashMap。

如果我们用单独的特性去描述不同的实现的话,将在以下列出:

1)      HashMap作为一个hash表的实现,它的key和value是无序的。

2)      TreeMap是基于红黑树的结构来实现的,并且它的key是有序的。

3)      LinkedHashMap保证了插入的顺序。

4)      和HashMap相比较,HashTable是同步的。

  在这里给了我们一个使用HashMap的理由,因为HashTable是线程安全的,它的同步开销会非常大。


2.   HashMap

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

如果我们自定义了HashMap的key对象,那么就需要重写它的equals和hashCode方法,如下:

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());
		}
	}
}

输出:

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 takes it. This does not make sense, because now we are confused how many white dogs are really there.

       注意这里,我们错误的增加了“white dogs”两次,可是HashMap仍然取到了它。这显然没有意义,因为放入很多的“white dogs”会令我们感到混淆


The Dog class should be defined as follows:

Dog这个类应该定义如下:

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

现在的输出是:

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

       原因是HashMap不允许有两个重复的元素。默认情况下,在使用Object类的时候,hashCode和equals方法就已经被实现了。默认的hashCode方法会针对与不同的对象给予不同的integer的值,并且equals方法则会去参考两个相同对象的引用来返回true。

如果你不熟悉这块的话,可以去看 thehashCode() and equals() contract这篇文章。


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

       阅读 mostfrequently used methods for HashMap这篇文章,包括迭代,打印等。       


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.

    一个TreeMap的key是有序的。首先让我们来通过以下的例子去了解“键排序”的思想。

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());
		}
	}
}

输出:

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.

因为TreeMap是键排序的,所以它的键对象是能够和其他对象进行比较的,这就是为什么它实现了Comparable接口。例如,你用String来作为key值,因为String实现了Comparable接口。


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

让我们去改变Dog类,使它能够进行比较。

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());
		}
	}
}


输出:

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

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

         它是键排序的,也就是dog的size。

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

       如果 ”Dog d4 = new Dog(“white”, 10);” 被替换成 “Dog d4 = newDog(“white”, 40);”,那么将会输出:


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!

这个结果是因为TreeMap现在使用了compareTo方法来比较key值,不同的size会构建出不同的dog。


4. Hashtable

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

在Java Doc中:

HashMap类除了不是同步的,并且允许null值以外,它基本上和HashTable大致相同。


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是HashMap的一个子类。这意味着他继承了HashMap的特性。另外,链式列表保证了插入元素的顺序。


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

让我们把介绍HashMap代码中的HashMap类替换成LinkedHashMap类。

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());
		}		
	}
}

输出:

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.

不同的是如果我们使用HashMap来运行的话,将会输出下面格式——插入的顺序将会被打乱

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


该文章摘录自http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/

您的回应...

相关话题

查看全部

也许你感兴趣

换一批

热门标签

更多