经常会用到map中的 keySet() 方法,得到的是 java.util.concurrent.ConcurrentHashMap$KeySetView
对象。
然后使用 contains
方法发现会抛出 NullPointerException
可是通过打印日志发现 set 是有数据的。
查看源码发现
public static class KeySetView<K,V> extends CollectionView<K,V,K>
implements Set<K>, java.io.Serializable {
private static final long serialVersionUID = 7249069246763182397L;
private final V value;
KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
super(map);
this.value = value;
}
/**
* {@inheritDoc}
* @throws NullPointerException if the specified key is null
*/
public boolean contains(Object o) { return map.containsKey(o); }
}
原来当传入的key会为空的时候,会抛出 NullPointerException
解决方案
防御性编程建议
String target = ...;
if (target != null && set.contains(target)) {
// 业务逻辑
}
前期阻止了 null 传递到 set.contains(param)