Re: TreeSet.contains and an OVERLOADED equals...works?
LastHope wrote:
Hi to all,
today I've come across this strange behaviour in my code, and I tried
to set-up a little test...I don't know if it's already known or
not...didn't find any of this through google,except of this:
http://forum.java.sun.com/thread.jspa?threadID=549491&messageID=2680884
However, no code is specified...
Take this class as an example:
---
public class Tipo implements Comparable<Tipo>
{
private int tipo;
public Tipo(int tipo)
{
this.tipo = tipo;
}
public boolean equals(Tipo t) {return tipo == t.tipo;}
public int compareTo(Tipo t) {return tipo - t.tipo;}
}
Tipo has two versions of equals, "public boolean equals(Tipo t)",
declared in Tipo, and "public boolean equals(Object o)", declared in
Object and inherited by Tipo. These methods are inconsistent - the
inherited Object method considers each object to be equal to itself and
nothing else.
The compiler chooses between these two methods, based on the compile
time type of the argument. If the argument is of type Object, the Object
version is used, even if, at run time, it happens to reference a Tipo.
I think this explains all your results, but ask again if there is
anything that still does not make sense.
Incidentally, overriding equals without also overriding hashCode to keep
it consistent is scary. Maybe you don't intend to use any hash data
structures now, but it is a bug waiting to happen.
Patricia