Java 8 类型推断 - 如何减少泛型构造函数?

Java 8 Type Inference - How reduction is done for generic constructors?

我正在阅读 java 8 语言规范类型推断。它说

List<String> ls = new ArrayList<>()

先降价

ArrayList<α> -> List<String>

然后到

α <= String

最后到

α = String

我很难理解如何减少约束

ArrayList<α> -> List<String> to α <= String

已导出。如果有人可以使用 java 8 语言规范指出逻辑,那将是一个很大的帮助。

Here's link 减少


感谢#Holger 的解释。以下是我对

推导的看法
new ArrayList<> -> List<String> to ArrayList<α> -> List<String>

如有错误请指正

首先找到我们使用的构造函数的临时方法#15.9.3

  • Otherwise, the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the expression.

  • If the class instance creation expression uses <> to elide class type arguments, a list of methods m1...mn is defined for the purpose of overload resolution and type argument inference.

然后用#18.5.2导出

ArrayList<α> -> List<String>

因为是一个多边形表达式并且没有任何通配符类型参数;

  • Otherwise, the constraint formula ‹R θ → T› is reduced and incorporated with B2.

很高兴你没有问如何从 new ArrayList<>() → List<String>ArrayList<α> → List<String> 因为,虽然看起来很明显,但根据应用 §18.2.1,我们会发现它需要讨论整个 §15.9.3,然后是对 §18.5.2 的讨论。

ArrayList<α> → List<String> 开始更容易:

§18.2.2. Type Compatibility Constraints

A constraint formula of the form ‹S → T› is reduced as follows:

  • … (five inapplicable bullets omitted)

  • Otherwise, the constraint reduces to ‹S <: T›.

§18.2.3. Subtyping Constraints

A constraint formula of the form ‹S <: T› is reduced as follows:

  • … (five irrelevant bullets omitted)

  • Otherwise, the constraint is reduced according to the form of T:

    • If T is a parameterized class or interface type, or an inner class type of a parameterized class or interface type (directly or indirectly), let A1, ..., An be the type arguments of T. Among the supertypes of S, a corresponding class or interface type is identified, with type arguments B1, ..., Bn. If no such type exists, the constraint reduces to false. Otherwise, the constraint reduces to the following new constraints: for all i (1 ≤ i ≤ n), ‹Bi <= Ai›..

所以ArrayList<α> → List<String>首先被简化为ArrayList<α> <: List<String>,然后,由于List<String>是参数化接口,因此识别出ArrayList<α>对应的超类型,这将是List<α>,然后,约束被简化为每个对应类型参数的一组约束(这里我们只有一个),所以我们得到 α <= String.