Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
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 The Software Craftsman this week in the Agile 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: 1512

HashCode and equals. Just like Map.

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

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().
Have you tried LearnNowOnline?
subject: On Sets