先说结果:hashMap的key可以为null,另外两个不可以。此外HashTable和ConcurrentHashMap的value也不能为null。
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put(null,"1");
System.out.println(map.get(null));
Hashtable hashtable = new Hashtable<>();
hashtable.put(null,"1");
System.out.println(hashtable.get(null));
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put(null,"1");
System.out.println(concurrentHashMap.get(null));
}
原因:二义性问题
因为ConcurrentHashMap和HashTable是线程安全的,一般使用在并发环境下,你一开始get方法获取到null之后,再去调用containsKey方法,没法确保get方法和containsKey方法之间,没有别的线程来捣乱,刚好把你要查询的对象设置了进去或者删除掉了。
HashMap的key丢失或重复:
测试的时候发现的现象,如果HashMap的key为null,则在map转json的过程中key为null的结果会丢失 public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put(null,"1");
map.put("null","2");
// hutool
System.out.println(JSONUtil.toJsonStr(map)); // 输出结果为{"null":"2"}
// fastjson
System.out.println(JSON.toJSONString(map)); // 输出结果为{"null":"2"}
// 解决map的key值为null数据丢失,但是会导致同时出现两个key相同的情况
String toJSON = JSON.toJSONString(map, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
System.out.println(toJSON); // 输出结果为{"null":"1","null":"2"}
}
参考链接:https://blog.csdn.net/qq_25112523/article/details/86030205
6163

被折叠的 条评论
为什么被折叠?



