• Post Reply Bookmark Topic Watch Topic
  • New Topic

Set determine an object is duplicate ?  RSS feed

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an object doesn't implement Comparable and equal(), how a Set determine an object is duplicate or not ?

Thanks.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the objects don't implement the Comparable interface and you didn't specify a Comparator then it will throw an Exception.
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally your objects don't have to implement Comparable, unless you are using a TreeSet.

As for "implementing equal()", as you put it: I assume you are referring to the "public boolean equals(Object o)" method which allows anything to determine whether that object is equal to another object. Well, that's the answer. The set will call the "equals(anotherObject)" method and if it returns true then the two objects are equal, as far as it's concerned, otherwise not.

So if there are rules defining when two objects of a particular class are to be considered equal, then that class should have an equals(Object) method which overrides the default version inherited from Object.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and, since many Set implementations use the hash code to find their elements, you must override hashCode() whenever you override equals().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!