实现独立的方式来查看地图是否包含空键

问题描述:

我有一个接收实现 Map 接口的参数的API。我需要检查这个 Map 是否包含任何 null 键。问题是有 Map 的某些实现,例如 ConcurrentHashMap ,如果调用 contains(null)

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.

什么是一个好的,与实现无关的方式来查看一个遵守 Map 接口的对象是否包含 null 键?

What is a good, implementation independent way to see if an object that adheres to the Map interface contains a null key or not?

请注意,我不能使用 keySet 并检查是否包含null,因为 ConcurrentHashMap 实际上只是将 keySet 包装到自身上,最后再次调用包含

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.

任何想法都会非常感激。我宁愿不使用 instanceOf ,因为当你必须转弯的情况下,这么多不同类型的 Map

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

我认为这会做到:

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);
}