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");
}
}
}
In the code snippet above I am expecting one of the following two things to happen:
There will be a compiler error, because
iis autoboxed toIntegerandjis autoboxed toLongand the declaration of the methodtestrequires that both of its arguments are of the same type.Both
iandjto be autoboxed to Long and the code to compile and run showing thatiandjare equal.
But what happens actually is i is autoboxed to Integer and j is autoboxed to Long and the code compiles without error. Doesn't this contradict with the declaration of test? What is the reason to allow such code?