Re: TreeSet.contains and an OVERLOADED equals...works?
LastHope wrote:
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 agree to what you say, but what I can't understand is why in my
example it seems that the compiler chooses two different methods while
applying the same arguments:
---
System.out.println("Does the list contain t2 (which is 'equal' to t1)?
" + tipoList.contains(t2));
// returns false, which means that the argument is
treated as an Object, and so the Object version was used
System.out.println("So, Does the set contain t2 (which is 'equal' to
t1)? " + tipoSet.contains(t2));
// returns true, which means that the argument is
treated as a Tipo, and so the Tipo version was used
I don't think TreeSet<Tipo> contains uses equals at all. It uses
compareTo(Tipo) from the Comparable<Tipo> interface. TreeSet contains is
declared to throw "ClassCastException - if the specified object cannot
be compared with the elements currently in the set."
ArrayList, on the other hand, only requires an Object, and uses the
Object equals method in its comparison.
More generally, any time equals(Object), equals(otherType), and
compareTo are not consistent with each other you need to look VERY
closely at documentation, and in some cases at implementation, to work
out what is going to happen. Do you really need them to be inconsistent?
Patricia