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

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/

时间: 2024-10-18 04:26:01

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap的相关文章

【Simple Java】HashMap vs TreeMap vs Hashtable vs LinkedHashMap

Map是一个重要的数据结构,本篇文章将介绍如何使用不同的Map,如HashMap,TreeMap,HashTable和LinkedHashMap. Map概览 Java中有四种常见的Map实现,HashMap,TreeMap,HashTable和LinkedHashMap,我们可以使用一句话来描述各个Map,如下: HashMap:基于散列表实现,是无序的: TreeMap:基于红黑树实现,按Key排序: LinkedHashMap:保存了插入顺序: Hashtable:是同步的,与HashMa

HashMap、TreeMap、Hashtable、LinkedHashMap区别

HashMap 允许设置key和value为null,key存放是乱序的,不支持线程的同步,即任一时刻可以有多个线程同时写HashMap;可能会导致数据的不一致.如果需要同步,可以用 Collections的synchronizedMap方法使HashMap具有同步的能力,或者使用ConcurrentHashMap,访问速度快,因为它根据key的HashCode 值来存储数据 public static void main(String[] args) { System.out.println(

[Java] HashMap、TreeMap、Hashtable排序

Java中对Map(HashMap,TreeMap,Hashtable等)的排序时间 首先简单说一下他们之间的区别: HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度.HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null.非 首先简单说一下他们之间的区别: HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度.HashMap

Java 容器 &amp; 泛型:五、HashMap 和 TreeMap的自白

Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Java 容器的文章这次应该是最后一篇了:Java 容器 系列. 今天泥瓦匠聊下 Maps. 一.Map回顾 Map,又称映射表,是将键映射到值的对象.有四种实现Map接口并且经常使用的Map集合为:HashMap,TreeMap,Hashtable 和 LinkedHashMap. 泥瓦匠记忆宫殿: 1.一个映射不包含重复的键. 2.每个键最多只能映射到一个值. 二.HashMap HashMap

HashMap、HashTable、LinkedHashMap、TreeMap使用和区别

1.HashMap继承AbstractMap 实现Map接口,Map在java.util包中是独立的接口,不是继承Collection接口,继承Collection接口的有: /** * @see Set * @see List * @see Map * @see SortedSet * @see SortedMap * @see HashSet * @see TreeSet * @see ArrayList * @see LinkedList * @see Vector * @see Coll

JavaSE入门学习37:Java集合框架之Map接口及其实现类HashMap和TreeMap

一Map接口 Map接口中的每个成员方法由一个关键字(key)和一个值(value)构成.Map接口不直接继承于Collection接口,因 为它包装的是一组成对的"键-值"对象的集合,而且在Map接口的集合中也不能有重复的key出现,因为每个键只能与 一个成员元素相对应. Map接口定义了存储"键(key)--值(value)映射对"的方法.实现Map接口的类用来存储键值对.Map接口中包含 了一个keySet()方法,用于返回Map中所有key组成的Set集合.

HashMap、HashTable、LinkedHashMap和TreeMap用法和区别

Java为数据结构中的映射定义了一个接口java.util.Map;它有四个实现类,分别是HashMap Hashtable LinkedHashMap 和TreeMap Map用于存储键值对,根据键得到值,因此不允许键重复,值可以重复. HashMap就是一张hash表,键和值都没有排序: TreeMap以红-黑树结构为基础,键值按顺序排列: LinkedHashMap保存了插入时的顺序: Hashtable是同步的(而HashMap是不同步的).所以如果在线程安全的环境下应该多使用HashM

Android——ArrayList 、LinkList、List 区别 &amp; 迭代器iterator的使用 &amp; HashMap、Hashtable、LinkedHashMap、TreeMap

ArrayList .LinkList.List 区别 & 迭代器iterator的使用 & HashMap.Hashtable.LinkedHashMap.TreeMap 一.几个List类型 1.大学数据结构中ArrayList是实现了基于动态数组的数据结构,LinkList基于链表的数据结构. 2.对于随机访问get和set,ArrayList优于LinkList,因为LinkedList要移动指针. 3.对于新增和删除操作add和remove,LinkList比较占优势,因为Arr

【Java】Map杂谈,hashcode()、equals()、HashMap、TreeMap、LinkedHashMap、ConcurrentHashMap

参考的优秀文章: <Java编程思想>第四版 <Effective Java>第二版 Map接口是映射表的结构,维护键对象与值对象的对应关系,称键值对. > hashcode()和equals() hashcode()和equals()即用于识别对象的身份. 在HashMap或类似的实现中,查找一个对象,是通过hashcode()返回的散列值映射到一个范围内的下标,在通过equals()比较此下标连接的链表是否存在相同的对象. 简单来说,hashcode()用于参考.快速定位