Joona said:
Except that it will throw a ClassCastException when its parameter is of
a class that can't be compared to, when it should simply return false.
Exactly. Good catch! I was about to say it was fine, and hadn't
thought about those conditions. Same thing with equals(null), which
should return false, where compareTo(null) should throw
NullPointerException.
Try this:
public boolean equals(Object o) {
try {
return compareTo(o)==0;
}
catch (Exception e) {
return false;
}
}
Have you considered what happens when you run this code and compareTo
throws an IndexOutOfBoundsException because of some radically corrupted
program state? You end up hiding the failure for longer, making some
arbitrary choice that may lead incorrect data to be fed to some other
part of the program, with very bad results. Better to write:
public boolean equals(Object o)
{
if (!(o instanceof ThisClass)) return false;
else return (compareTo(o) == 0);
}
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation