问题
I have an API that receives a parameter which implements the Map
interface. I need to check to see if this Map
contains any null
key. The problem is there are certain implementations of Map
, such as ConcurrentHashMap
which throw NPE if you call contains(null)
on them.
What is a good, implementation independent way to see if an object that adheres to the Map
interface contains a null
key or not?
Note that I can't use keySet
and check to see if that contains a null, because ConcurrentHashMap
actually just wraps the keySet
onto itself and ends up calling contains
again underneath.
Any ideas would be much appreciated. I would rather not use instanceOf
since that tends to look ugly when you have to corner case so many different types of Map
s
回答1:
I think this would do the trick:
private static Map<String, String> m = new ConcurrentHashMap<>();
public static void main(String[] args) {
boolean hasNullKey = false;
try {
if (m != null && m.containsKey(null)) {
hasNullKey = true;
}
} catch (NullPointerException npe) {
// Relies on the fact that you can't add null keys to Map
// implementations that will throw when you check for one.
// Add logging etc.
}
System.out.println("Does map have null key? " + hasNullKey);
}
回答2:
new HashSet<K>(map.keySet()).contains(null);
or if you don't want to copy all the keys:
boolean containsNull = false;
for (K k : map.keySet()) {
if (k == null) {
containsNull = true;
break;
}
}
来源:https://stackoverflow.com/questions/27512362/implementation-independent-way-to-see-if-a-map-contains-null-key