https://www.cnblogs.com/williamjie/p/9099141.html
HashMap的key和value都可以为null
Hashtable的key和value都不能为null
@Test
public void test1() {
Map<Object, Object> map = new HashMap<>();
map.put("a", "aaa");
map.put("b", "bbb");
map.put("c", "ccc");
map.put("d", null);
map.put(null, "eee");
System.out.println(map.get("d")); //null 值为null
System.out.println(map.get("e")); //null 没有key
System.out.println(map.get(null)); //null 没有key
System.out.println(map.containsKey(null));
}
@Test
public void test2() {
Hashtable<Object, Object> table = new Hashtable<>();
table.put("a", "aaa");
table.put("b", "bbb");
table.put("c", "ccc");
// table.put("d", null); //NullPointerException
// table.put(null, "eee"); //NullPointerException
System.out.println(table.get("a")); //null 值为null
System.out.println(table.get("b")); //null 没有key
System.out.println(table.contains("aaa"));
System.out.println(table.containsValue("aaa"));
}
网友评论