Java Dailly Tip: Is checking for key existence in HashMap always necessary

Java Dailly Tip: Is checking for key existence in HashMap always necessary

Problem

Suppose we have a HashMap object with 100 records and we want to improve search performance.

If our HashMap is used very often, checking if a given key exists will cause a heavy load. Instead, maybe it is better to catch an exception if the key does not exist? This can reduce the amount of operations in the HashMap.

It may not be a very good programming practice, but it does help to reduce the number of operations on HashMap. Or maybe I'm wrong.

Solution

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

@Override
public boolean containsKey(Object key) {
    Entry m = getEntry(key);
    return m != null;
}

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

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

Share this Post