How <T> deals with String and Integer

I can't figure out how T takes Integer and String. As here, in the mapping function, T deals with both Integer and String. How does this code work?

class firstBase { <T> void display(T give_num, T give_String) { System.out.println("The given number is = " + give_num + " The given String is = " + give_String); System.out.println("The class of given number is = " + give_num.getClass() + " The class of given_String is = "+give_String.getClass()); } } public class testanonymous { public static void main(String[] args) { firstBase fb = new firstBase(); fb.display(100, "xyz"); } } 
+5
source share
1 answer

You call the raw form of the method, which basically equals

 void display(Object give_num, Object give_String) 

Here are both arguments that you fit, because 100 is autoboxed by Integer (which is a subclass of Object ), and "xyz" is String (which is a subclass of Object )

To use Generics correctly, you need to do:

 fb.<String>display(100, "xyz"); 

or

 fb.<Integer>display(100, "xyz"); 

In both cases, you will notice that the code does not compile because the compiler will know about your intention to replace T with Integer / String in Runtime, but the parameter types will not be the same type provided.

+5
source

Source: https://habr.com/ru/post/1206809/


All Articles