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));1.答案是什么
2.解释一下原理,我头都大了
谢谢高手们哦
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.答案是什么
2.解释一下原理,我头都大了
谢谢高手们哦
返回的int类型和x正好符合
d:返回的是double
b 返回的类型和int不匹配
a 好像字符串不太合适吧 等高手来解释。。
帮你顶下。。
你接受的时候是一个Int型,那个T就表示是int
D排除,而B,Double比Int的类型大,接受应该用Double才对,
至于A,我也不清楚可以不可以
主要x.compareTo(y)这个,我不知道能通过不~
呵呵~~~希望能为楼主解惑~
A. Object x = t.findLarger(123, “456”);
会被自动装箱成t.findLarger(Comparable, Comparable),
因为返回值是Object,所以不会出现编译错,但最后在调用Integer的compareTo实现时,String不能转成Integer出错.
B. int x = t.findLarger(123, new Double(456));
B通不过编译的。123 和 new Double(456),装箱后会成为Number, Number,
返回值由Number转int出错
D. int x = (int) t.findLarger(new Double(123), new Double(456));
同上,返回值由Double转int出错
T必须是两个传入参数的父类,123自动转换成Integer,所以Integer和Double的公共父类市Object,所以B答案的返回值类型市Object,不能与int匹配
scjp我也考完了但是找工作没人问的
有点郁闷