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
}
}
}
通常,
compareTo()
方法以字典顺序打印,但是当compareTo()
方法如上述代码中那样被覆盖时,它如何比较两个字符串? 最佳答案
根据您的compareTo方法,所有对象彼此相等,因为您始终返回0,所以当您尝试将两个Drink对象添加到TreeSet时,将仅添加第一个对象,因为Set不允许重复。
这样的实现实际上比较名称是有意义的:
public class Drink implements Comparable<Drink> {
public String name;
@Override
public int compareTo(Drink o) {
return name.compareTo(o.name);
}
...
}