HashMap 非线程安全的
HashTable线程安全的
package Collections.Map; import java.util.HashMap; public class HashMapTest { public static void main(String[] args) {
HashMap<String,String> map = new HashMap<String,String>(); //测试覆盖【值被覆盖】
map.put("a", "apple");
map.put("a", "animal");
System.out.println(map.get("a")); //测试键为空值【键可以为空】
map.put(null, "desk");
System.out.println(map.values()); //测试值为空【值为空】
map.put("b", null);
System.out.println(map.keySet()); //null可以做为键
}
}
package Collections.Map; import java.util.Hashtable; public class HashTableTest { public static void main(String[] args) {
Hashtable<String,String> table = new Hashtable<String,String>(); table.put("a", "apple");
table.put("a", "animal");
System.out.println(table.get("a")); table.put(null, "desk");
System.out.println(table.values()); table.put("b", null);
System.out.println(table.keySet());
}
}
HashMap 可以将key或value设为null
HashTable不能将key或value设为null