This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes equals()method and compareTo() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "equals()method and compareTo() method" Watch "equals()method and compareTo() method" New topic

equals()method and compareTo() method

pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
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

Joined: Oct 27, 2005
Posts: 20279

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 ]

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: equals()method and compareTo() method
It's not a secret anymore!