This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "equals()method and compareTo() method" Watch "equals()method and compareTo() method" New topic
Author

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
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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 ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals()method and compareTo() method
 
Similar Threads
equals and compareTo
String and String Buffer
hashCode(), compareTo() and equals()
help with loop
What does this mean?