1. public class Test {
2. public <T extends Comparable> T findLarger(T x, T y) {
3. if(x.compareTo(y) > 0) {
4. return x;
5. } else {
6. return y;
7. }
8. }
9. }
and:
22. Test t = new Test();
23. // insert code here
Which two will compile without errors when inserted at line 23?
(Choose two.)
A. Object x = t.findLarger(123, “456”);
B. int x = t.findLarger(123, new Double(456));
C. int x = t.findLarger(123, new Integer(456));
D. int x = (int) t.findLarger(new Double(123), new Double(456));

解决方案 »

  1.   

    答案是Answer: AC。
       讲讲为什么,越详细越好,,谢谢~~
      

  2.   

    1. public class Drink implements Comparable {
    2. public String name;
    3. public int compareTo(Object o) {
    4. return 0;
    5. }
    6. }
    and:
    20. Drink one = new Drink();
    21. Drink two = new Drink();
    22. one.name= “Coffee”;
    23. two.name= “Tea”;
    23. TreeSet set = new TreeSet();
    24. set.add(one);
    25. set.add(two);
    A programmer iterates over the TreeSet and prints the name of each
    Drink object.
    What is the result?
    A. Tea
    B. Coffee
    C. Coffee
    Tea
    D. Compilation fails.
    E. The code runs with no output.
    F. An exception is thrown at runtime.
    Answer: B难道这里编译器认为one和two是同一个对象吗??
      

  3.   

    TreeSet的API中有如下一句话:基于 TreeMap 的 NavigableSet 实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。也就是说TreeSet中的元素的相同与否有里面对象的Comparator决定,由于你的Comparator中的cmpareTo()方法恒返回的是0也就是恒等所以在用迭代器遍历你的TreeSet的时候会认为里面的两个对象是同一个对象所以只访问了第一个就输出了Coffee.