有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。在Java中将映射转换为ConcurrentMap时发生并发错误

我有一个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);

我没有任何错误。没有NullPointerException有没有安全的方法从Map<String,Object>ConcurrentMap<String,Object>


共 (2) 个答案

  1. # 2 楼答案

    如果您查看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();