user2693979
user2693979

Reputation: 2542

How knows JVM the generics type paramter without arguments?

I have a generics factory method.

public static <T> List<T> create(){
    return new ArrayList<T>();
}

But it hasn't arguments/parameters.

I don't give the type paramter for the function, but it knows the appropriate type without any arguments.

public static void main(String[] args){
    List<Integer> intlist = create();  //it is an Integer List
    List<String> stringlist = create();  //it is a String List
}

Upvotes: 1

Views: 359

Answers (2)

newacct
newacct

Reputation: 122439

One point of view is that when the generic parameter is not explicitly given, it is inferred. Usually, it is inferred from the arguments, but when there are no arguments, in limited cases (e.g. variable declaration) it can be inferred from the left side.

Another point of view is that, when the generic parameter is not explicitly given, the compiler doesn't really care what the parameter is exactly. After all, the type parameter does not affect the compiled bytecode at all. It just needs to be able to prove that there exists some type parameter that would make it work; and it doesn't care any more. There could be multiple valid type parameters for a situation; but it doesn't care which one is "used", because it has no effect on the result. In this case, since the method takes no arguments and returns a List<T> where T is a generic for the method, as long as it's used in a context that takes a List, it is valid, because regardless of List<what exactly> is desired, a valid T exists (T = whatever type parameter is desired). So the compiler doesn't actually need to check the type parameter at all in this case.

Upvotes: 1

rgettman
rgettman

Reputation: 178263

The JVM doesn't know the generic type parameter due to type erasure.

The Java compiler is able to infer that T should be Integer or String in your examples, because it has access to the generic type information on the types of the variables you have declared.

Upvotes: 6

Related Questions