Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How <T> is dealing here with String and Integer

Tags:

java

generics

I am not able to understand how T is taking Integer and String. As here in display function T is dealing with both Integer and String. How this code is working?

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");
    }
}
like image 337
swati Avatar asked Nov 13 '14 14:11

swati


1 Answers

You're invoking the raw form of the method, which is basically equal to

void display(Object give_num, Object give_String)

Here, both of the arguments you provide fit, because 100 is autoboxed to Integer (which is a subclass of Object) and "xyz" is a String (which is a subclass of Object)

To use Generics correctly, you have to do:

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

or

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

In both cases, you'll note that the code doesn't compile, because the compiler will be aware of your intent to replace T with Integer/String at Runtime, but the parameter types are not of the same provided type.

like image 75
Konstantin Yovkov Avatar answered Oct 12 '22 01:10

Konstantin Yovkov