Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this generic code in java compile? [duplicate]

Tags:

java

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?

like image 338
TheLogicGuy Avatar asked Feb 09 '17 10:02

TheLogicGuy


People also ask

How does generic work in Java?

A generic type is a class or interface that is parameterized over types, meaning that a type can be assigned by performing generic type invocation, which will replace the generic type with the assigned concrete type.

How does Java implements generics why?

Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically.

What generics?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Is String a subtype of object?

String is a subtype of Object , because the String class is a subclass of the Object class. int is not a subtype of Object , because none of Java's primitive types are subtypes of any reference type.


1 Answers

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.)

like image 70
khelwood Avatar answered Nov 16 '22 00:11

khelwood