A method parameterized by one type takes two types

Maybe I missed something, and maybe my assumptions were wrong, but I thought that when I declare a parameterized method with type T , then no matter how many variables exist with this type, it is still the same type. But I see that this compiles, and it contradicts my opinion.

 static <T> void f(T a, T b) { } public static void main(String[] args) { f(Integer.MIN_VALUE, "..."); } 

So, if my method is parameterized by one type, and I use this type in two parameters, why does it allow me to send two objects with two completely different types? I think it comes down to considering T as an Object ?

+6
source share
1 answer

Although Integer and String are two different types, they still have a common supertype. Serializable

To check this, return T ,

 static <T> T f(T a, T b) { return null; } Serializable s = f(Integer.MIN_VALUE, "..."); // compiles 

The compiler will allow (or output, not sure about the technical term) the most specific type. For instance,

 Number number = f(Integer.MAX_VALUE, BigDecimal.ONE); 

The type is now permitted by Number , because both types are subtypes of Number , as well as Serializable , as well as Object , of course.

+4
source

All Articles