Implementation independent way to see if a map contains null key

断了今生、忘了曾经 提交于 2019-12-10 21:04:59

问题


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 Maps


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!