Kaushik Baral wrote:Hello all,
can someone explain what happens inside set interface (Collection) to avoid duplicate data.
thanks a lot in advance.
Erm...nothing. An interface doesn't have any code. And Collection is NOT a Set, and doesn't provide any guarantees about uniqueness.
As to implementations, I suspect that it's down to the individual Set. From the documentation, it would appear that AbstractSet doesn't include any specific code to prevent duplicates, it merely requires that extensions "follow the rules".
It's fairly straightforward though: Set has a contains(Object) method which AbstractSet implements in a naive fashion (it actually uses AbstractCollection's, which simply iterates over all the elements in the Set looking for a matching element). It seems likely therefore that add(Object) could probably simply be implemented asand classes that need a faster version of contains() will override it with an implementation that makes sense for their particular type of Set.
The trouble is that that implementation is likely to be very specific to the type of Set, so it's virtually impossible to explain "what happens" unless we know what type of Set you're talking about.
Isn't it funny how there's always time and money enough to do it WRONG?