I read online that HashSet
uses HashMap
as its underlying data structure.
And HashMap
uses ArrayList
as its underlying data structure with each item in the list being an object of LinkedList
or a tree
.
What is the time complexity when you initialize a HashSet
this way? Can it be O(1)? If not, why?
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(2);
list.add(6);
list.add(0);
HashSet<Integer> set = new HashSet<>(list);
HashMap
does not use an ArrayList
as its underlying data structure.
HashMap
maintains a hashtable built out of a primitive array, and uses a hybrid strategy of a linked list or a tree for handling collisions. You can see this by examining the source code for java.util.HashMap
.
Since, to build a hashtable, you need to invoke the hash function on every entry to determine the hash location, the minimum bound is O(N). The worst case is for pathologically distributed keys (e.g. every key is a collision), which would be substantially worse than O(N). Since the Java 8 implementation degrades to a balanced tree instead of a linked list in the worst case, your worst case runtime would be O(N log N). (In previous versions of Java, which used linear probing, I believe worst case would have been O(N²)).
Your List
can contain n
number of Objects which might be all duplicate or all unique or mixture.
The property of a HashSet
collection is that it contains no duplicate objects.
Therefore, the time complexity to traverse the List
and add each object to the HashSet
would be O(n)
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