Re: problem with Sets
Hi,
Heres and example I did - the results are :
true
true
false
[A$Identity@1cdeff]
To be of any actual use you have to correct the compare and equals
methods.
Regards,
Chris
public class A {
private static class IdentityComparator implements Comparator{
public int compare(Object a, Object b){
// implement this correctly
return 0; // as a test this always indicates equality
}
}
private static class Identity {
public boolean equals(Object obj){
// implement this correctly
return true; // as a test this always indicates equality
}
}
public static void main(String[] args){
Set identities = new java.util.TreeSet<Identity>(new
IdentityComparator());
Identity id1 = new Identity();
Identity id2 = new Identity();
System.out.println(id1.equals(id2));
System.out.println(identities.add(id1));
System.out.println(identities.add(id2));
System.out.println(identities);
}
}
bassel wrote:
greeting everyone,
I have a problem with sets, according to the API documentation
Class TreeSet<E>
---------------------------
public boolean add(E e)
Adds the specified element to this set if it is not already
present. More formally, adds the specified element e to this set if the
set contains no element e2 such that (e==null ? e2==null :
e.equals(e2)). If this set already contains the element, the call
leaves the set unchanged and returns false.
new I have this code:
-----------------------------
Set identities = new java.util.TreeSet<Identity>();
System.out.println(id1.equals(id2));
System.out.println(identities.add(id1));
System.out.println(identities.add(id2));
output is:
------------
true
true
true
where's the problem???
regards,
Bassel