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

解决方案 »

  1.   

    public int compareTo(Object o){
    return 0;
    }
    compareTo()返回0,表示两个对象相同.
    Set中不允许存在相同/重复的对象,后set()的对象如果和之前set()的对象相同(通过compareTo比较),那么将覆盖原来的对象
    所以Set中实际上只有一个Drink的实例,就是Tea.
    因此选A
      

  2.   

    看了半天觉得这题目怪怪的.只能靠自己的理解了.在实现 Comparable接口后再重写compareTo(Object o)因为compareTo方法只有一个返回就是0.那就是无论如何都是会让这两个值相等.如果是sort方法排序这两个对象的话,那肯定这两个对象是相等的.我自己的理解是推广而言,那这里就是两者相等了...偶也说不清楚..觉得有点迷糊.关键应该是在compareTo里.可能是把前者和后者比较,因为返回的肯定是0.两者肯定相等,那前者就被等于了后者....有点感觉像是在凑答案
      

  3.   

    sey不是要保证不能有相同的元素啊..
    它是根据compareTo()来判断还是根据equals()来判断的啊..!!!!我运行过了,答案是B
      

  4.   

    应该是b,add(one)起作用,add(two)的时候,经过判断,就不会加进去了应该!!所以用迭代器的时候,只有第一次加进去的!!!!
      

  5.   

    应该是A。因为TreeSet的内部是由一个TreeMap来支持的,该TreeMap的Key就是TreeSet的元素。调用TreeSet的add()函数其实相当于调用TreeMap的put()函数。而put函数会将以前的值替换掉(如果有重复的话)。
      

  6.   

    终于看明白了。因为TreeSet内的那个TreeMap实例只会替换掉Value,而不会替换掉Key。
    而TreeSet的add(Object o)方法是这样的:
    public boolean add(E o) {
    return m.put(o, PRESENT)==null;
    }
    所以,Coffee做为TreeMap元素的key,不会被替换掉。
    鉴定完毕!
      

  7.   

    import java.util.*;
     
     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...所以解释好象不好理解。
      

  8.   

    System.out.println(set.contains(one));
    System.out.println(set.contains(two));
    这两个当然都返回true了!compareTo总是返回0的。这有什么不好理解……
      

  9.   

    建议大家去看TreeSet和TreeMap的源代码,Josh Bloch写的很清晰。