您的位置:首页 > 其它

HashMap, TreeMap, LinkedHashMap, Hashtable区别(一)

2013-10-29 00:00 387 查看
虽然都继承自Map接口,但是差别还是蛮大的。

对于容器类的研究,我想Thinking in Java的容器分类图说明的再明白不过。



接下来通过例子说明一下,具体的不同。

首先是对于null的处理。如下所示,K = Key, V = Value.注意Hashtable not HashTable

Class K null V null K null V null K not null V null
HashMap OK OK OK
Hashtable NO NO NO
TreeMap NO OK OK
LinkedHashMap OK NO NO
Java代码

import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.TreeMap;

public class MapCompare {
public static void main(String args[]) {

testNull();

}

public static void testNull(){
testHashMap();
testHashTable();
testTreeMap();
testLinkedHashMap();
}

public static void testHashMap() {
HashMap map = new HashMap();
//		map.put(null, null);
//map.put(null, "TEST");
map.put("TEST", null);
}

public static void testHashTable() {
try {
Hashtable map = new Hashtable();
//			map.put(null, null);
//			map.put(null, "TEST");
map.put("TEST", null);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void testTreeMap() {
try {
TreeMap map = new TreeMap();
//			map.put(null, null);
//			map.put(null, "TEST");
map.put("TEST", null);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void testLinkedHashMap() {
try {
LinkedHashMap map = new LinkedHashMap();
//			map.put(null, null);
//			map.put(null, "TEST");
map.put("TEST", null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: