Why does this generic code in java compile?

TheLogicGuy :
public static <T> T foo(T x, T x2) {
    return (T) (x + "   " + x2);
}

public static void main(String args[]) {
    System.out.println(foo(33, "232"));
}

I know T gets to be of the type that is passed in the parameter. But here there are two types. Which one of them is T?

and why the compiler doesn't force me to have the parameters of same type when I call foo?

khelwood :

It's legal because Integer and String have a common base type. T can be Object, so foo(T, T) will accept any two objects. 32 can be autoboxed to an Integer, which is a kind of Object. "232" is a String, which is a kind of Object.

(As pointed out by comments, for Integer and String, there is a closer common base-type, Serializable; but the principle is the same whichever base type the compiler resolves T to.)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=455624&siteId=1