public class Drink implements Comparable {
public String name;
@Override
public int compareTo(Object o) {
return 0;
}
@Override
public String toString() {
return name;
}
public static void main(String[] args) {
Drink one = new Drink();
Drink two = new Drink();
one.name = "Coffee";
two.name = "Tea";
TreeSet set = new TreeSet();
set.add(one);
set.add(two);
Iterator itr = set.iterator();
while(itr.hasNext()) {
System.out.println(itr.next()); //prints Tea
}
}
}
Usually, compareTo()
method prints in lexicographical order, but when compareTo()
method is overridden as in the above code then how it is comparing the two strings?
According to your compareTo method, all objects are equal to each other, since you always return 0, so when you try to add two Drink objects to your TreeSet, only the first one will be added, since a Set doesn't allow duplicates.
It would make more sense to have an implementation like this, that actually compares the names :
public class Drink implements Comparable<Drink> {
public String name;
@Override
public int compareTo(Drink o) {
return name.compareTo(o.name);
}
...
}