问题描述
class Test {
public static <T> boolean test(T a,T b) {
return a.equals(b);
}
public static void main(String[] args) {
int i = 0;
long j = 0;
if (!test(i,j)) {
throw new RuntimeException("i is not equal to j");
}
}
}
在上面的代码片段中,我期望发生以下两种情况之一:
但是实际上发生的是将j
自动装箱到i
,将Integer
自动装箱到j
,并且代码编译没有错误。这与Long
的声明不矛盾吗?允许使用此类代码的原因是什么?
解决方法
如果i
被装在Integer
上,而j
被装在Long
上,则以其通用类型调用方法test
仍然合法假定为java.lang.Number
,它是Integer
和Long
的超类型。
实际上,您可以使用 any 两个对象来调用test
方法,因为T
可以作为基本类型Object
。该方法上的泛型根本不限制其参数。