Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of HashMap.containsKey() in java?

I need to know: What is the time complexity of HashMap.containsKey() in java?

like image 904
Hossein Avatar asked Jan 19 '12 08:01

Hossein


People also ask

Is HashMap containsKey constant time?

From the API doc of HashMap: This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.

What is containsKey method in Java?

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.

Is containsKey faster than get?

It takes approximately the same amount of time to call get and containsKey, and it's virtually guaranteed that after you call containsKey, you're going to call get anyways, so you may as well cut out the middle man.

What is space complexity of HashMap in Java?

With HashMap, we can achieve an average time complexity of O(1) for the put and get operations and space complexity of O(n).


2 Answers

From the API doc ofHashMap:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.

Since containsKey() is just a get() that throws away the retrieved value, it's O(1) (assuming the hash function works properly, again).

like image 157
Michael Borgwardt Avatar answered Oct 07 '22 17:10

Michael Borgwardt


Generally O(1), but if we're using a bad hashCode function, we need to add multiple elements to one bucket so it can be O(n) in worst case.

like image 29
mishadoff Avatar answered Oct 07 '22 18:10

mishadoff