Java的一些字典是否可以存储 null?
爪哇的一些字典是否可以存储 null?
今天我就用 HashMap、Hashtable、ConcurrentHashMap、TreeMap 这几种开发中常用数据结构来测试下。
结论在前
其实大家看下源码测试下就可以得到以下结论:
- HashMapkey 和 value 都可以为空
- Hashtablekey 和 value 都不能为空
- ConcurrentHashMapkey 和 value 都不能为空
- TreeMapkey不能为 null,value 可以为空
为空时抛出的都是 NPE (NullPointException)
HashMap
测试代码
Map<String, String> hashMap = new HashMap<>();
hashMap.put(null, null);
System.out.println(hashMap.get(null));
System.out.println(hashMap);
输出
null
{null=null}
结论
hashMap key 可以 存储 null, value 也可以 存储 null
Hashtable
测试代码
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put(null, "");
System.out.println(hashtable);
hashtable.put("", null);
System.out.println(hashtable);
输出
测试 hashtable.put(null, "");输出

测试 hashtable.put("" , null);输出

原因
测试 key是否为空,put 方法中获取 null 的 hashCode方法,会抛出NPE

测试 value是否可以为空,put方法里会有判断

ConcurrentHashMap
ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put(null, null);
System.out.println(concurrentHashMap);
结果

结论
key 和 value 都不能为空
原因
ConcurrentHashMap的put方法中有判断

TreeMap
测试代码
TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put(null, "");  // NPE
treeMap.put("", null);  // 可以通过
treeMap.put(null, null); // NPE
System.out.println(treeMap);
输出

原因
用默认的比较方式比较key,所以key不能为 null

但是存储 value 可以为 null
结论
key不能为 null,value 可以为 null
结论在后
- HashMapkey 和 value 都可以为空
- Hashtablekey 和 value 都不能为空
- ConcurrentHashMapkey 和 value 都不能为空
- TreeMapkey不能为 null,value 可以为空
为空时抛出的都是 NPE (NullPointException)
转载自:https://juejin.cn/post/7043278442644635679




