I would like to use a generic type to ensure, that the arguments of a method are of the same type, like this:
public static <T> void x(T a, T b)
I would assume that the two arguments (a and b), that are passed to this method, would always have to be of the same type. But to my surprise I was able to pass arguments of any type (even primitives) to method x, as if T is erased to Object, no matter what arguments are passed.
The only work-around I found so far, was to use 'extends' like this:
public static <T, U extends T> void x(T a, U b)
But although I can live with it, it is not what I wanted.
Is there a way to use a generic type to force the type of all arguments of a method?
Generic Functions: We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method.
Which of these is an correct way of defining generic method? Explanation: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type. 5.
If I understand correctly, one way to do it is to explicitly specify the type of T instead of letting the compiler infer its type to be of the most direct superclass in the case of two objects of different types being passed in as arguments. Take something like this, for example:
public class Test { public static void main(String[] args) { Test.x(5.0, 5); // This works since type is inferred to be Number Test.<Integer>x(5, 5); // This works since type is stated to be Integer Test.<Integer>x(5.0, 5); // This doesn't; type is stated to be Integer and Double is passed in } public static <T> void x(T a, T b) { } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With