Question 181
Given:
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));答案是:AC偶感觉不对啊~(虽然偶的感觉经常是错的- -)A中,int和String也可以比的?
而且在D中,两个Double为什么不可比?- -

解决方案 »

  1.   

    D是最明显的了,返回类型是T,强制转为int,显然不对。
      

  2.   

    D可以改成这样double x = t.findLarger(new Double(123), new Double(456));
      

  3.   

    B:
    int x = t.findLarger(123, new Double(456)); 
    也是返回类型不确定。
      

  4.   

    对于A
    Object x = t.findLarger(123, “456”); 
    编译器分析可以把123转为Integer,“456”为String,返回类型可以规约到Object,所以编译器检查不出什么问题,可以正确编译。
    不过运行时会出问题。