File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes On Sets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "On Sets" Watch "On Sets" New topic

On Sets

deepak carter
Ranch Hand

Joined: Feb 19, 2011
Posts: 165
In an interview i was asked that Sets doesnt allow duplicate.What logic does it implements inside so that it doesnt allow duplicate???

Anayonkar Shivalkar

Joined: Dec 08, 2010
Posts: 1545

HashCode and equals. Just like Map.

Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Manoj Kumar Jain
Ranch Hand

Joined: Aug 22, 2008
Posts: 194

I think Set use hashCode() and equals() methods to check if object is already inserted or not.

The hashCode() determines the bucket number, while equals() determines if the one of the objects already inserted in the bucket is equal to the willing to insert object.

Do not wait to strike till the iron is hot; but make it hot by striking....
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

HashSets use HashCode and equals().

SortedeSets, such as TreeSet, use Comparable.compareTo() or Comparator.copmare().

Some set that you or I write might do something totally different. It's completely implementation-dependent, although the Set contract specifies that it must behave as if it uses equals().
I agree. Here's the link:
subject: On Sets
It's not a secret anymore!