• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals and compareTo method difference?

 
Tanu Gulati
Ranch Hand
Posts: 113
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To me, equals and compareTo both do the same basic job(comparing the objects) why does java have two different methods for doing the same work ( i know i am missing some thing here but want to know what).

some of my questions
1.) can one class have both equals and compareTo (if yes what is the use)
2.) which one is always better to use in a class, "equals" or "compareTo"


 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15452
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals() checks if two objects are the same or not and returns a boolean.

compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is "less than", "equal to" or "greater than" the other. Not all objects can be logically ordered, so a compareTo() method doesn't always make sense.

Note that equals() doesn't define the ordering between objects, which compareTo() does.

1. Yes.
2. Neither is better, it depends on what functionality your class needs.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple of additions:

- There is always an equals() method, because it's defined in Object. You only override it if you want different behaviour from the default (which is "are these refencing the same object?"). You don't always have a compareTo() method.

- If you do have a compareTo method, it is strongly recommended that you also provide an equals method that is consistent with it. That is, if a.compareTo(b) == 0, then a.equals(b) (and vice-versa).
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals is much broader than compareTo. I can say that an apple is not equal to a pear. I can't go comparing them though.

This is reflected in the argument type: Object for equals, T for Comparable<T>.
 
Tanu Gulati
Ranch Hand
Posts: 113
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper, Matthew, Rob
thanks to All. you guys are wonderful!!
 
Campbell Ritchie
Sheriff
Pie
Posts: 49841
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote: . . . it is strongly recommended that you also provide an equals method that is consistent with it. That is, if a.compareTo(b) == 0, then a.equals(b) (and vice-versa).
Recommended, not compulsory.

Example:
A lot of people rant about the BigDecimal#compareTo(java.math.BigDecimal) not being "consistent with equals", but I believe that is the correct way to implement it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic