Reputation: 7008
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?
Upvotes: 1
Views: 116
Reputation:
It is not comparing the string in this as thecomapareTo()
method is returning 0 (meaning objects are equal) so set.add(two)
will be considered as duplicated and only the first value added will be printed.
Try reversing the order of addition of values to the set and you will get your answer
Upvotes: 1
Reputation: 393781
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);
}
...
}
Upvotes: 2
Reputation: 1160
The overridden compareTo method is used for customize comparison. In this function, you compare two objects based on your business logic and on the basis of your logic, you return -1,0 or 1, where -1 represents invoking object is smaller than the invoked object while _1 represents the other way. 0 represents that both the objects are equal.
In your code, right now it is not putting any logic. Its just returning a prototype value. You might put something like that in your code
return name.compareTo((String)o);
which will be the default functionality if you don't put your custom override method.
Upvotes: 0