File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "On Sets" Watch "On Sets" New topic
Author

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
Bartender

Joined: Dec 08, 2010
Posts: 1512
    
    5

HashCode and equals. Just like Map.


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

Joined: Aug 22, 2008
Posts: 193

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
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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: http://aspose.com/file-tools
 
subject: On Sets