public class Drink implements Comparable{
public String name;
public int compareTo(Object o){
return 0;
}and:Drink one=new Drink();
Drink two=new Drink();
one.name="Coffee";
two.name="Tea";
TreeSet set=new TreeSet();
set.add(one);
set.add(two);A programmer iterates over the TreeSet and prints the name of each Drink object.what is the rusult?A Tea
B.Coffe
C.Coffe
Tea
D.Compilation fails.
E.the code runs with no output
F.An exception is thrown at runtime
public String name;
public int compareTo(Object o){
return 0;
}and:Drink one=new Drink();
Drink two=new Drink();
one.name="Coffee";
two.name="Tea";
TreeSet set=new TreeSet();
set.add(one);
set.add(two);A programmer iterates over the TreeSet and prints the name of each Drink object.what is the rusult?A Tea
B.Coffe
C.Coffe
Tea
D.Compilation fails.
E.the code runs with no output
F.An exception is thrown at runtime
return 0;
}
compareTo()返回0,表示两个对象相同.
Set中不允许存在相同/重复的对象,后set()的对象如果和之前set()的对象相同(通过compareTo比较),那么将覆盖原来的对象
所以Set中实际上只有一个Drink的实例,就是Tea.
因此选A
它是根据compareTo()来判断还是根据equals()来判断的啊..!!!!我运行过了,答案是B
而TreeSet的add(Object o)方法是这样的:
public boolean add(E o) {
return m.put(o, PRESENT)==null;
}
所以,Coffee做为TreeMap元素的key,不会被替换掉。
鉴定完毕!
class Drink implements Comparable{
public String name;
public int compareTo(Object o){
return 0;
}public static void main(String arg[]){
Drink one=new Drink();
Drink two=new Drink();
one.name="Coffee";
two.name="Tea";
TreeSet set=new TreeSet();
set.add(one);
set.add(two);
System.out.println(set.contains(one));
System.out.println(set.contains(two));
Iterator i=set.iterator();
System.out.println(i.next());
System.out.println(set.first());
System.out.println(set.last());
}
}
答案是:
true
true
Drink@35ce36
Drink@35ce36
Drink@35ce36
Press any key to continue...所以解释好象不好理解。
System.out.println(set.contains(two));
这两个当然都返回true了!compareTo总是返回0的。这有什么不好理解……