• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals()method and compareTo() method

 
pradeepta chopra
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it is said that while the equals() method must always take Object type as an argument while compareTo() should take the argument we are sorting upon.
why is it so??
 
Rob Spoor
Sheriff
Pie
Posts: 20753
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only since Java 5.0.

It is true that equals always needs Object as its type. I guess it's so you can check if an object is equal to any other object. It's like asking: is this apple the same as that orange? The answer is false obviously, but it's still a valid question.

For Comparable in Java 1.4 and before you also needed to pass Object. Most implementations would throw a ClassCastException though if an instance to another incompatible object is given. Since Java 5.0 you need to specify where you can compare yourself to, although mostly it's the class itself: X implements Comparable<X>.
The reason is quite clear: what sense does it make to compare yourself with something that is nothing like you? It's like asking: what is the result if I compare this apple with that orange? Everybody knows you can't compare apples and oranges!
[ September 01, 2008: Message edited by: Rob Prime ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic