首页  

ConcurrentHashMap使用注意点     所属分类 java 浏览量 989
ConcurrentHashMap key value 都不能为 null 
HashMap key 和 value 都可以为 null 
把 HashMap 数据 全部 put 到  ConcurrentHashMap ,注意空指针!!!
// maybe NPE !!!
concurrentHashMap.putAll(hashMap);


ConcurrentHashMap
final V putVal(K key, V value, boolean onlyIfAbsent) {
     if (key == null || value == null) throw new NullPointerException();
     


	public static void main(String[] args) throws Exception {	
		// ConcurrentHashMap key value 都不能为 null 
		Map<String,String> map = new ConcurrentHashMap<>();
		map.put("a", "1");
		try{
		    // java.lang.NullPointerException
		    map.put("a", null);
		}catch(Throwable e){
	            System.out.println("value-null,"+e);
		}
		
		try{
	            // java.lang.NullPointerException
		    map.put(null, "1");
		}catch(Throwable e){
	            System.out.println("key-null,"+e);
		}
		
		System.out.println("\n\n\n");
		
		// HashMap key 和 value 都可以为 null 
		Map<String,String> map2 = new HashMap<>();
	        map2.put("a", "1");	
		map2.put("a", null);
	        map2.put(null, "1");
	    
		System.out.println("map2="+map2);
		
		// 往 ConcurrentHashMap 里 添加 HashMap 数据 ,有可能NPE
		map.putAll(map2);

	}


上一篇     下一篇
springboot最核心的三个注解

springboot面试题

springboot自动配置原理和实例

SpringCloud VS Dubbo

Jedis的几种使用方式

zookeeper节点属性中的三个zxid