- HashMap支持key是null,value也为null,在从Map中取出key对应的value后,要做一个空判断,防止出现空指针;
ConcurrentHashMap不支持key和value为null,containsKey也不支持传空,所以ConcurrentHashMap在put值进去和判断是否有值的时候一定要做空判断。在工作中如果使用ConcurrentHashMap时,建议使用抽出几个工具方法,省得判空方法散落在各处;
/**
* @param concurrentHashMap ConcurrentHashMap
* @param key String
* @param value String
*/
public static void putValue(ConcurrentHashMap<String, Object> concurrentHashMap, String key, String value) {
if (concurrentHashMap == null || key == null || value == null) {
return;
}
concurrentHashMap.put(key, value);
}
/**
* @param concurrentHashMap ConcurrentHashMap
* @param key String
* @return boolean
*/
public static boolean containsKey(ConcurrentHashMap<String, Object> concurrentHashMap, String key) {
if (key == null || concurrentHashMap == null) {
return false;
}
return concurrentHashMap.containsKey(key);
}