HashMap, TreeMap, LinkedHashMap, Hashtable區別(一)

雖然都繼承自Map接口,可是差異仍是蠻大的。 java

對於容器類的研究,我想Thinking in Java的容器分類圖說明的再明白不過。 spa

接下來經過例子說明一下,具體的不一樣。 code

首先是對於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();
		}
	}
}
相關文章
相關標籤/搜索