given
public class Drink implements Comparable {
public String name;
public int compareTo(Objcet 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 result?

解决方案 »

  1.   

    老兄,你到底想干什么,没有说清楚
    如果,你是想让name的值进行排序的话
    你Drink实现了Comparable 必须重写compareTo具体怎么写,上网很多,自己去看看吧
      

  2.   

    只会返回一个Drink 对象,对象是coffee.因为Drink 实现了Comparable ,里面的这个compareTo只返回0;
    TreeSet就认为放进去的两个大小是相同的。这个题,主要是考Comparable 接口。
      

  3.   

    为什么返回0 TreeSet就认为放进去的两个大小是相同的?
    因为返回0 所以就一个coffee?
    那为什么是coffee 不是tea呢?
    可以再讲得详细点么?
      

  4.   

    看看这个add方法就知道了为什么是CoffeeAdds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
      

  5.   

    这个问题挺不错啊,我一开始以为会是COFFEE TEA,自己跑了一下结果是COFFEE 研究了一下,问题出在return 0上Set 接口是一个不包含重复元素的 collection。根据 equals 操作进行定义,但 TreeSet 实例将使用其 compareTo(或 compare)方法执行所有的键比较,因此,从 set 的角度出发,该方法认为相等的两个键就是相等的。Drink实现Comparable接口,并且compareTo方法永远返回0,因此,向set中添加多个Drink时都认为是相同的,
    因为它用compareTo比较是否相同,这样,后面的Drink都无法添加进set将return 0改为其它值就会得到不同结果
    但不管怎样COFFEE都应在TEA之前输出啊,TreeSet是按照自然排序的
      

  6.   

    对,是coffee,运行一下就知道了。
      

  7.   

    对,是coffee,运行一下就知道了。
      

  8.   

    对,是coffee,运行一下就知道了。