虽然都继承自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(); } } }