Comparable vs. Equals

by Mark Shead on March 27, 2005

Agylen: Comparable vs equals has a nice discussion of how compareTo is used in Sets.

If you don’t understand how Java is going to use your compareTo and your equals methods you can run into a problem with Sets. Basically you shouldn’t have a compareTo() method that returns 0 unless equals() returns true.

Since a Set only allows once instance of each object, it will ignore the addition of any objects it already contains. If your object implements the Comparator interface the Set will check the compareTo method not the equals method.

It is common to write compareTo methods that only look at one field. For example, you might want to sort Person objects by their last name and then first name. If you only check the last and first name field, then comparing two John Smiths would return 0 even if they were different objects. This would cause the Set to evaluate them as the same object and prevent you from adding the second John Smith to the Set.

People Found This When Looking For:

  • compareto vs equals (6)
  • java compareTo vs equals (5)
  • java equals vs compareto (4)
  • java comparable vs equals (3)
  • equals vs compareto in java (2)
  • equals vs compare in java (1)
  • java Comparable equals (1)
  • comparable and equals (1)
  • java comparator equels (1)
  • java comparator vs comparable (1)

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

Previous post:

Next post: