TreeSet.contains and an OVERLOADED equals...works?
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;}
}
---
My error: equals doesn't support generics, and this is overloading,
not overriding the method...however, try this "test suite" :
---
import java.util.*;
public class TestTipaggio
{
public static void main(String[] args)
{
Tipo t1 = new Tipo(3);
Tipo t2 = new Tipo(3);
System.out.println("Are t1 and t2 'equal'? " + t1.equals(t2));
Object o1 = t1;
System.out.println("Are o1 and t2 'equal'? " + o1.equals(t2));
System.out.println("Are t2 and o1 'equal'? " + t2.equals(o1));
List<Tipo> tipoList = new ArrayList<Tipo>();
System.out.println("Can I add t1 to the list? " + tipoList.add(t1));
System.out.println("Does the list contain t2 (which is 'equal' to
t1)? " + tipoList.contains(t2));
Set<Tipo> tipoSet = new TreeSet<Tipo>();
System.out.println("Can I add t1 to the set? " + tipoSet.add(t1));
System.out.println("Can I add t2 to the set? " + tipoSet.add(t2));
System.out.println("So, Does the set contain t2 (which is 'equals'
to t1)? " + tipoSet.contains(t2));
}
}
---
My output (compiled both with jdk1.5.0_03 and jdk 1.6.0_01) is always
like this:
---
Are t1 and t2 'equal'? true
Are o1 and t2 'equal'? false
Are t2 and o1 'equal'? false
Can I add t1 to the list? true
Does the list contain t2 (which is 'equal' to t1)? false
Can I add t1 to the set? true
Can I add t2 to the set? false //weird
So, Does the set contain t2 (which is 'equals' to t1)? true //weird
---
It seems like it's calling the overloaded method, differently from the
ArrayList...and this doesn't respect what it says on the javadoc
public boolean contains(Object o)
Returns true if this set contains the specified element. More
formally, returns true if and only if this set contains an element e
such that (o==null ? e==null : o.equals(e)).
Am I right? In any case, on my machine, the contains of TreeSet
behaves differently from the contains of ArrayList...
Thank you
LastHope