Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check the existence of a HashMap key

In Java, having a HashMap fully filled in with data of such form:

HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(1000000, 1);

what is faster when checking the existence of a random key, say 100:

if (map.get(100) == null))

or

if (!map.containsKey(100))

?

Question is interesting from the micro-optimization point of view.

like image 253
Sophie Sperner Avatar asked Feb 09 '13 13:02

Sophie Sperner


People also ask

How do I find the value of a map key?

HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How do you find if there is a null key in HashMap?

containsKey() to determine if the Map entry has a key entry. If it does and the Map returns null on a get call for that same key, then it is likely that the key maps to a null value.

What if key is not present in map Java?

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.


2 Answers

The two differs only in return type except that map.get(key) may return you null in case if its a key, however map.containsKey(key) will return you boolean which could be used to distingush the two possible cases of map.get(key) returning null.

like image 185
dShringi Avatar answered Sep 28 '22 09:09

dShringi


The containsKey should be very slightly slower because it results in an extra function call (it just calls getEntry) (it could get optimised away, I'm not sure whether Java will do so). containsKey looks like:

public boolean containsKey(Object key) {
  return getEntry(key) != null;
}

But note that containsKey could on the other hand be very slightly faster on other Map implementations (but probably not those in the standard Java API).

Generally my implementations look like: (avoiding the need for containsKey)

int[] arr = map.get(100);
if (arr == null) // doesn't exist
  // do stuff
else // exists
  // do stuff with arr

The below would definitely be slower than the above: (if the items you look for exist a reasonable amount of the time)

if (!map.containsKey(100)) // doesn't exist
  // do stuff
else // exists
{
  int[] arr = map.get(100);
  // do stuff with arr
}

Edit: Thanks to zvzdhk for providing the source of containsKey. I should actually have checked.

like image 21
Bernhard Barker Avatar answered Sep 28 '22 10:09

Bernhard Barker