It runs in O(1) expected time, as any hash table (assuming the hash function is decent). It is backed by a HashMap where the key is the Object.

Two objects might have the same hash code, but the HashSet wouldn't think they are identical, unless the equals method for these objects says they are the same (i.e. returns true).

The contains method calls (indirectly) getEntry of HashMap, where key is the Object for which you wish to know if it's in the HashSet.

As you can see below, two objects can be stored in the HashMap/HashSet even if their key is mapped to the same value by the hash function. The method iterates over all keys that have the same hash value, and performs equals on each one to find the matching key.

final Entry<K,V> getEntry(Object key) {
         int hash = (key == null) ? 0 : hash(key.hashCode());
         for (Entry<K,V> e = table[indexFor(hash, table.length)];
              e != null;
              e = e.next) {
             Object k;
             if (e.hash == hash &&
                 ((k = e.key) == key || (key != null && key.equals(k))))
                 return e;
         }
         return null;
     }
Answer from Eran on Stack Overflow
Top answer
1 of 2
104

It runs in O(1) expected time, as any hash table (assuming the hash function is decent). It is backed by a HashMap where the key is the Object.

Two objects might have the same hash code, but the HashSet wouldn't think they are identical, unless the equals method for these objects says they are the same (i.e. returns true).

The contains method calls (indirectly) getEntry of HashMap, where key is the Object for which you wish to know if it's in the HashSet.

As you can see below, two objects can be stored in the HashMap/HashSet even if their key is mapped to the same value by the hash function. The method iterates over all keys that have the same hash value, and performs equals on each one to find the matching key.

final Entry<K,V> getEntry(Object key) {
         int hash = (key == null) ? 0 : hash(key.hashCode());
         for (Entry<K,V> e = table[indexFor(hash, table.length)];
              e != null;
              e = e.next) {
             Object k;
             if (e.hash == hash &&
                 ((k = e.key) == key || (key != null && key.equals(k))))
                 return e;
         }
         return null;
     }
2 of 2
36

The worst-case performance of contains will be O(log n) for Java 8, and O(n) for Java 7, but average case closer to O(1). This is because the hashset is backed by a hashmap, and thus has the same efficiency as hashmap lookup (ie, HashMap.get(...)). The actual mapping in a hashmap is constant time (O(1)), but the need to handle collisions brings the cost to log n. That is, multiple elements that hash to the same array index must be stored in a secondary data structure (aka bucket), and it is this bucket that determines the worst-case performance. In Java, hashmap collision-handling is implemented using a self-balanced tree.

Self-balanced trees guarantee O(log n) for all operations, hence, insertion and lookup in hashmap (and hashset) has a total cost of O(1) + O(log n) = O(log n). The use of a self-balanced tree for collision-handling was introduced in Java 8 as an improvement over chaining (used until java 7), which uses a linked-list, and has a worst case of O(n) for lookup and insertion (as it needs to traverse the list). Notice that chaining would have constant time for insertion (as opposed to lookup), since elements can be added to a linked list in O(1), but the set property (no duplicates) is imposed on the linked-list in the case of hashmap, and it thus need to traverse the linked-list also in the case of insertion to ensure that the element does not already exist in the list/bucket, and we end up with O(n) for both insertion and lookup.

References:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html

Buckets containing a large number of colliding keys will store their entries in a balanced tree instead of a linked list after certain threshold is reached. (https://www.nagarro.com/en/blog/post/24/performance-improvement-for-hashmap-in-java-8)

🌐
Reddit
reddit.com › r/java › what is the complexity of contains method of hashset?
r/java on Reddit: What is the complexity of contains method of HashSet?
December 9, 2021 -

As far as I know, it's o(1) but my professor told me it is o(n) He said that it makes a linear search in the set. I don't think it's correct. But I need some proof to show my professor to get my mark from the question. I made some searches and some guys on stackoverflow.com say that it's o(1). So in short how can I prove to my professor it o(1) to get a mark?

" All right guys, I objected and shared my search with him. He confirmed that it's o(1). there is a misunderstood. He taught it's an ArrayList because of my handwriting. So the problem is fixed. Thanks for your all effort."

Discussions

Time complexity of HashSet.contains in Java - Stack Overflow
Because .contains has to check every element of the set so it would have a time complexity of O(n) and it is looped. ... Not necessarily looped. For example, if "difference" is a set represented by a hashtable, there is usually no looping. ... This depends on the type of difference. If it is a hashed colleciton, like a HashSet... More on stackoverflow.com
🌐 stackoverflow.com
Time complexity for searching in java HashSet and TreeSet .

odds of hashcodes for two strings becoming same

Read this: https://dzone.com/articles/what-is-wrong-with-hashcode-in-javalangstring#:~:text=The%20collisions%20in%20hashcode%20are,strings%20have%20the%20same%20hashcode.

how the search in this HashSet works in worst case

HashSet is implemented by wrapping over a HashMap (source: javadoc);

On Java 7, HashMap is implemented by Separate Chaining with LinkedList in each array slot (bucket), so worst case happens when ALL element is chained on a single array slot, making it a linked list with O(n) elements; Searching in a linked list gives worst case time complexity O(k*n) where k is the time complexity of ".equals()" method;

On Java 8, HashMap is implemented by Separate Chaining with Self-balanced BST (e.g. AVL Trees) in each array slot (bucket), so worst case happens when ALL element is chained on a single array slot, making it a balanced BST with O(n) elements; Searching in a balanced BST gives worst case time complexity O(k*lg(n)) where k is the time complexity of ".equals()" method;

I may be wrong tho

More on reddit.com
🌐 r/javahelp
4
12
August 20, 2020
Time complexity of set in Java - Stack Overflow
Can someone tell me the time complexity of the below code? a is an array of int. Set set = new HashSet (); for (int i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
What is the complexity of contains method of HashSet?
It is O(1) in practice, but in the very very worst case (when you have objects with a broken hash function) it is O(n). It can be considered O(m) with m being the size of your object you're inserting: hash function calculation scales linearly with object size. But that's insignificant in practice, and not relevant when talking about Sets and Collections. More on reddit.com
🌐 r/java
33
3
December 9, 2021
🌐
Medium
medium.com › @chakravartyutkarsh › understanding-why-hashset-provides-o-1-search-time-complexity-15cee2f96cec
Understanding Why HashSet Provides O(1) Search Time Complexity | by Utkarsh Chakravarty | Medium
October 14, 2024 - One of the most efficient data structures for storing unique elements is the HashSet. When it comes to searching, HashSet is known for its O(1) average time complexity, which means that searching for an element is incredibly fast.
🌐
Baeldung
baeldung.com › home › java › java collections › performance of contains() in a hashset vs arraylist
Performance of contains() in a HashSet vs ArrayList | Baeldung
April 4, 2025 - Before moving ahead, make sure you are familiar with Big-O notation. On average, the contains() of HashSet runs in O(1) time. Getting the object’s bucket location is a constant time operation.
🌐
CodeSignal
codesignal.com › learn › courses › mastering-algorithms-hashmaps-two-pointers-and-beyond-in-java › lessons › complexity-analysis-and-optimization-using-hashset-in-java
Complexity Analysis and Optimization Using HashSet in Java
The average time complexity for removal is ... import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class HashSetRemoveExample { public static void main(String[] args) { Set<Integer> mySet = new HashSet<>(Arrays.asList(1, 2, 3, 4)); mySet.remove(3); // O(1) mySet.remove(5); // O(1) but this will have no effect since 5 is not in the set System.out.println(mySet); // Prints: [1, 2, 4] (order may vary) } } ... The contains method checks for the existence of an element in a HashSet.
🌐
Hyperskill
hyperskill.org › learn › step › 19918
HashSet internals
Hyperskill is an educational platform for learning programming and software development through project-based courses, that helps you secure a job in tech. Master Python, Java, Kotlin, and more with real-world coding challenges.
🌐
LinkedIn
linkedin.com › pulse › understanding-hashset-linkedhashset-treeset-java-saeed-anabtawi-
Understanding HashSet, LinkedHashSet, and TreeSet in Java
June 13, 2023 - The time complexity for basic operations is almost the same as HashSet, i.e., O(1). It also allows one null element. ... java import java.util.LinkedHashSet; public class Main { public static void main(String[] args) { LinkedHashSet<String> ...
🌐
javaspring
javaspring.net › blog › what-is-the-time-complexity-performance-of-hashset-contains-in-java
Java HashSet.contains() Time Complexity: Is It Constant? + Hash Collision Risks Explained — javaspring.net
In Java, HashSet is a go-to collection for storing unique elements and performing fast lookups, insertions, and deletions. A common assumption among developers is that operations like contains() run in constant time (O(1)).
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 68715390 › time-complexity-of-hashset-contains-in-java
Time complexity of HashSet.contains in Java - Stack Overflow
For example, if "difference" is a set represented by a hashtable, there is usually no looping. ... This depends on the type of difference. If it is a hashed colleciton, like a HashSet, then a contains() operation takes constant time.
🌐
Medium
medium.com › @rastogitanishka216 › understanding-hashset-in-java-76840f153036
HashSet in Java. Introduction | by Tanishka | Medium
February 29, 2024 - The time complexity of basic operations in HashSet is as follows: Addition (add()): O(1) average case, O(n) worst case · Removal (remove()): O(1) average case, O(n) worst case · Search (contains()): O(1) average case, O(n) worst case · HashSet ...
🌐
CodingTechRoom
codingtechroom.com › question › java-hashset-contains-time-complexity
What Is the Time Complexity of HashSet.contains() in Java? - CodingTechRoom
The HashSet.contains(Object) method in Java generally offers a time complexity of O(1), providing constant time performance for membership checks under typical circumstances.
🌐
Reddit
reddit.com › r/javahelp › time complexity for searching in java hashset and treeset .
r/javahelp on Reddit: Time complexity for searching in java HashSet and TreeSet .
August 20, 2020 -

I know in average case the time complexity is O(1) for HashSet and O(lgn) for TreeSet . But for HashSrt when the hashcode for two objects matches then it will search comparing the objects using equal method . But I want to search for strings creating a HashSet<String > . Can some one tell me what are the odds of hashcodes for two strings becoming same and how the search in this HashSet works in worst case . Thank in advance.

🌐
Quora
quora.com › What-is-the-time-complexity-of-HashSet
What is the time complexity of HashSet? - Quora
Answer (1 of 2): There is a stupid answer which makes you pass interviews and exam. Then there is the right answer that makes you an Engineer. This question was probably asked as homework question - so for you it is poof. It dos not require any “non constant” operation and hence the ...
🌐
DZone
dzone.com › data engineering › ai/ml › hashset vs. treeset vs. linkedhashset
HashSet vs. TreeSet vs. LinkedHashSet
March 29, 2013 - hashset is implemented using a hash table. elements are not ordered. the add, remove, and contains methods has constant time complexity o(1). treeset is implemented using a tree structure(red-black tree in algorithm book). the elements in a ...
🌐
Quora
quora.com › What-is-the-difference-in-the-time-complexity-of-HashSet-and-HashMap-The-below-code-was-throwing-time-limit-exceed-with-HashMap-but-not-with-HashSet-Can-anyone-answer
What is the difference in the time complexity of HashSet and HashMap? The below code was throwing time limit exceed with HashMap but not with HashSet. Can anyone answer? - Quora
Answer: I see that you have used map.containsValue to check for repetition of a number. HashMaps hash the key and not value to determine the index in the lookup table for that key,value pair. That is how Retrieving by key becomes an O(1) operation. Trying to retrieve by value is like asking a has...
🌐
CodeSignal
codesignal.com › learn › courses › hashing-dictionaries-and-sets-in-java › lessons › mastering-java-hashset-an-in-depth-exploration-of-implementation-and-complexity-analysis
Mastering Java HashSet: An In-depth Exploration of ...
The space complexity of a HashSet is linear (O(n)), where n is the number of elements contained in the HashSet. Each element occupies its distinctive bucket. ... import java.util.HashSet; class Solution { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); ...
🌐
CompleteEra
completeera.com › hashset-time-complexity-for-add-and-remove-understanding-its-efficiency
HashSet Time Complexity for Add and Remove: Understanding Its Efficiency – CompleteEra
April 30, 2026 - 🚀 HashSet Time Complexity for Add & Remove: How Efficient Is It? (With Examples!) TL;DR: HashSet offers average-case O(1) time complexity for both add and...
🌐
Baeldung
baeldung.com › home › java › java collections › time complexity of java collections
Time Complexity of Java Collections | Baeldung
September 24, 2025 - Benchmark 1000 10,000 100,000 .add() ... 0.008 0.013 0.009 · As we can see, the scores remain almost the same for each operation. When we compare them with the HashMap test outputs, they look the same as well. As a result, we confirm that all the tested methods run in constant O(1) time...
🌐
Medium
medium.com › @rasikadandawate.55555 › best-ways-to-minimize-time-complexity-and-space-complexity-in-java-d60217398e7b
Best ways to Minimize Time Complexity and Space Complexity of an Algorithm In Java! | by Rasika Dandawate | Medium
September 21, 2020 - So for this approach since we know that, all arithmetic and logical operation take O(1) time and loop takes O(n) time and Hashset takes O(1) and also functions contains() and add() takes O(1) time so , Our overall time Complexity becomes O(n). ...