Key existence check in HashMap

552,824

Solution 1

Do you ever store a null value? If not, you can just do:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // No such key
}

Otherwise, you could just check for existence if you get a null value returned:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // Key might be present...
    if (map.containsKey(key)) {
       // Okay, there's a key but the value is null
    } else {
       // Definitely no such key
    }
}

Solution 2

You won't gain anything by checking that the key exists. This is the code of HashMap:

@Override
public boolean containsKey(Object key) {
    Entry<K, V> m = getEntry(key);
    return m != null;
}

@Override
public V get(Object key) {
    Entry<K, V> m = getEntry(key);
    if (m != null) {
        return m.value;
    }
    return null;
}

Just check if the return value for get() is different from null.

This is the HashMap source code.


Resources :

Solution 3

Better way is to use containsKey method of HashMap. Tomorrow somebody will add null to the Map. You should differentiate between key presence and key has null value.

Solution 4

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

Solution 5

Just use containsKey() for clarity. It's fast and keeps the code clean and readable. The whole point of HashMaps is that the key lookup is fast, just make sure the hashCode() and equals() are properly implemented.

Share:
552,824
athena
Author by

athena

Updated on July 08, 2022

Comments

  • athena
    athena almost 2 years

    Is checking for key existence in HashMap always necessary?

    I have a HashMap with say a 1000 entries and I am looking at improving the efficiency. If the HashMap is being accessed very frequently, then checking for the key existence at every access will lead to a large overhead. Instead if the key is not present and hence an exception occurs, I can catch the exception. (when I know that this will happen rarely). This will reduce accesses to the HashMap by half.

    This might not be a good programming practice, but it will help me reduce the number of accesses. Or am I missing something here?

    [Update] I do not have null values in the HashMap.