| 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: 19216
|
|
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
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: equals()method and compareTo() method
|
|
|