Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

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 access 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?

 I do not have null values in the HashMap.

1 Answer

0 votes
by (46k points)

Do you ever saved a null value? If not, you can try this:

Foo value = map.get(key);

if (value != null) {

...

} else {

// No such key

}

Else, you could just verify check for existence if you receive 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

}

}

Related questions

0 votes
1 answer
asked Aug 26, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...