A look-up operation OR contains
for single can be O(n)
in worst-case right ? So, for n
elements look up in hashSet
will be O(n^2)
?
On average, the contains() of HashSet runs in O(1) time. Getting the object's bucket location is a constant time operation. Taking into account possible collisions, the lookup time may rise to log(n) because the internal bucket structure is a TreeMap.
Yes, accessing and finding an element in HashSet is O(1). HashSet stores elements using the hashing technique. Another important property of HashSet is that it contains only unique elements. For example you can check if the element already exists in HashSet.
It's both: O(n+k).
Both Vector and HashSet Collection implementation classes performed poorly compared to the ArrayList Collection implementation class. Vector scored 68 TPS on average, while HashSet scored 9200 TPS on average. On the other hand the ArrayList outperformed Vector and HashSet by far, resulting in 421000 TPS on average.
Yes, but it's really the worst case: if all the elements in the HashSet
have the same hash code (or a hash code leading to the same bucket). With a correctly written hashCode
and a normally distributed key sample, a lookup is O(1).
Yes, but the whole reason we have HashSets is that we encounter this worst case with very, very low probability, and it's usually much faster than the guaranteed nlogn for a heap or a (self-balancing) TreeSet, or the guaranteed n^2 for an unsorted list.
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