Question:
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
Answer: A
Explain:
Set 中 不允许有2个重复的对象 ,每个对象加入时都要调用对象的compareTo()方法,如果该方法返回0
则表示2个对象相同