From a official Java JDK1.7 guide, I got this quote, but I don't understand how it works. Can anyone explain? In other words, how does the diamond infer a Integer type when its passed an empty String?

MyClass<Integer> myObject = new MyClass<>("");

In this example, the compiler infers the type Integer for the formal type parameter, X, of the generic class MyClass. It infers the type String for the formal type parameter, T, of the constructor of this generic class.

有帮助吗?

解决方案 2

The quote indicates that there is a generic constructor in your class, which declares it's own type parameter. This is similar to how you create a generic method. The type parameter for the constructor is inferred from the argument you are passing while instantiating the class.

Here is a simple version of a class that matches that invocation:

 class MyClass<T> {
    <S> MyClass(S arg) {
        System.out.println(arg);
    }
 }

Now when you instantiate your class as in your code, the type parameter T is inferred as Integer, and type parameter S in constructor is inferred as String, from the argument you passed.

As for the diamond operator, from Java 7 onwards, you don't need to give the type arguments on while creating an instance of a generic class if you already are assigning a reference to a reference. The type argument will be inferred from the one used with the reference type, here Integer.

其他提示

The Integer part is inferred from the usage of the result of the constructor call - it's assigning to a variable of type MyClass<Integer>, hence the Integer part is inferred for the diamond. The constructor argument is irrelevant to this (unless it had to be the same type, in which case you'd just get a compilation error.)

Basically, if the type argument is clear from the context in which the expression is used (where "clear" means "following precise rules" of course) then the compiler will infer it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top