Lew wrote :
As Eric Sosman so ably pointed out, having 'equals()' in the interface would
do absolutely nothing to guarantee that the methods were consistent. All
that having the method in the interface does is guarantee that it's
implemented, not that it's consistent, and that condition would be trivially
met even if 'equals()' were not overridden in a 'Comparable' implementation.
Which goes for ANY method which is overriden or implemented. There is
an implied contract between the writer of the classes and the
programmer who implements the methods. That is what the Javadocs are
for, to explain what the method is supposed to do and return.
But having "hidden" requirements makes things harder. If I create an
interface for one of my classes, but do not include a method in the
interface which is supposed to return a fairly important value, I can
hardly complain that someone did not extend/implement that method.
This is one of the reasons we do have methods in Interfaces, to ensure
that someone will implement it, and by contract, implement it with the
desired actions.
If a class/interface needs both compareTo and equals to return
equivalent results for proper operation, then that class/interface
should _require_ it by using both in its defnintion.
And speaking of Javadocs, the compareTo method has the following gem:
"It is strongly recommended, but not strictly required that
(x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class
that implements the Comparable interface and violates this condition
should clearly indicate this fact. The recommended language is "Note:
this class has a natural ordering that is inconsistent with equals.""
So, while interesting, this discussion is beside the point. My original
thought and the class I posted will work. Some future maintainer will
just have to read my Javadocs.
)
I'm sorry to break this to you, but we as programmers are simply stuck with
having to show good sense in this matter. Follow the Javadocs. The Javadocs
give us the information we need to avoid trouble. Thank goodness for the
Javadocs. I guess we just have to do as the Javadocs suggest and make sure
that 'Comparable#compareTo()' is consistent with 'equals()', or be willing to
accept the consequences if we don't.
Ain't responsibility a bitch?
Now you are just getting snarky. Like you I have been doing this for
over 30 years in more languages than I can remember. I realize the
importance of reading docs and so on.
But in the midst of a coding haze I do not always break off to read
docs. The assumption is that the name of the class/method/parameters
makes sense, and all the requirements are exposed at the code level.
AFAIK this is the first time that I have been bitten by this
assumption.