This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
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: 1502

HashCode and equals. Just like Map.

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

Joined: Aug 22, 2008
Posts: 191

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
Similar Threads
Eclipse crashes everyday
Scrabble... it only takes a minute...
reading sms from inbox in a j2me application
How to make a JTree show restricted file hiearchies
regular expression which doesnt alllow *