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.
To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...
Map get() method If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.
To make sure key exists you should use HashMap#containsKey(key) function. Once key exists you may use HashMap#get(key) to get the value and compare it to null.
The Java HashMap containsKey() method checks if the mapping for the specified key is present in the hashmap. The syntax of the containsKey() method is: hashmap.containsKey(Object key) Here, hashmap is an object of the HashMap class.
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 } }
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With