Java 中将地图转换为 ConcurrentMap 时出错
Error in Converting a Map to ConcurrentMap in Java
我有一个Map<String,Object>
要转换成ConcurrentMap<String,Object>
Map<String,Object> testMap = new HashMap<String,Object>();
testMap.put("test", null); //This null causing issues in conversion
testMap.put("test2","123");
testMap.put("test3",234);
ConcurrentMap<String,Object> concMap = new ConcurrentHashMap<>(testMap);
我得到一个空指针异常。如果我复制到一个新的 HashMap<String,Object>
Map<String,Object> testMap = new HashMap<String,Object>();
testMap.put("test", null);
testMap.put("test2","123");
testMap.put("test3",234);
Map<String,Object> concMap = new HashMap<>(testMap);
我没有收到任何错误。有没有 Map<String,Object>
到 ConcurrentMap<String,Object>
的安全方法而不需要 NullPointerException
它在 documentation for ConcurrentHashMap
:
Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.
至于其他ConcurrentMaps,the only other implementation ConcurrentSkipListMap
, does not allow null either。
问题不在于将 HashMap
转换为 ConcurrentHashMap
。更多的是 ConcurrentHashMap
是空安全的,它不允许 null
值。从它的 documentation:
Like Hashtable
but unlike HashMap
, this class does not allow null
to be used as a key or value.
如果您查看 ConcurrentHashMap 的源代码,您会发现它不允许空键或空值 -
java.util.concurrent.ConcurrentHashMap#putVal
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
我有一个Map<String,Object>
要转换成ConcurrentMap<String,Object>
Map<String,Object> testMap = new HashMap<String,Object>();
testMap.put("test", null); //This null causing issues in conversion
testMap.put("test2","123");
testMap.put("test3",234);
ConcurrentMap<String,Object> concMap = new ConcurrentHashMap<>(testMap);
我得到一个空指针异常。如果我复制到一个新的 HashMap<String,Object>
Map<String,Object> testMap = new HashMap<String,Object>();
testMap.put("test", null);
testMap.put("test2","123");
testMap.put("test3",234);
Map<String,Object> concMap = new HashMap<>(testMap);
我没有收到任何错误。有没有 Map<String,Object>
到 ConcurrentMap<String,Object>
的安全方法而不需要 NullPointerException
它在 documentation for ConcurrentHashMap
:
Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.
至于其他ConcurrentMaps,the only other implementation ConcurrentSkipListMap
, does not allow null either。
问题不在于将 HashMap
转换为 ConcurrentHashMap
。更多的是 ConcurrentHashMap
是空安全的,它不允许 null
值。从它的 documentation:
Like
Hashtable
but unlikeHashMap
, this class does not allownull
to be used as a key or value.
如果您查看 ConcurrentHashMap 的源代码,您会发现它不允许空键或空值 -
java.util.concurrent.ConcurrentHashMap#putVal
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();