I am learning Java collection framework in Java, and got fair idea of various Classes and interfaces.
While going through Set interface, one of the implementations is HashSet (among others).
I am not able to understand what is the logic of implementing Set based on the Hash, what advantage does it serve?
Can anyone help me understand what is the need of Hash based implementation of Set in Java Collection Framework?
containswhere it needs to check if set already has element equal to the one which we want to add. Letting set organize elements in groups based on their hashes eliminate the need to check groups with different hash than of element which we are testing. So such set don't need to iterate over all elements, but only on those with similar hash code.set.add(x)set getx.hashcode()and now it knows which group of elements it should iterate, to look for equal element. It can skip iterating elements from other groups because it already knows that they have different hashes so they can't be equal toxelement. So if we have 4 groups equally populated then it speeds process 4 times because it needs to iterate max 1/4 elements. If we have 256 groups equally populated then performance also increases ~256 times (compared to iterating over all elements).