Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

On Sets

 
deepak carter
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashCode and equals. Just like Map.
 
Manoj Kumar Jain
Ranch Hand
Posts: 198
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic