我不能百分百理解为什么下面的代码不起作用:
package org.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public interface MyInt<E> {
}
public static final class MyNum<E> implements MyInt<E> {
private E privados;
}
public static void f(List<? extends MyInt> l) {
System.out.println("from List<?>");
}
public static void main(String[] args) {
var m = new MyNum();
List<MyNum> l = Arrays.asList(m);
ArrayList<MyInt> r = l.stream().collect(Collectors.toCollection(ArrayList<MyInt>::new));
f(r);
f(l.stream().collect(Collectors.toCollection(ArrayList<MyInt>::new)));
}
}
传递L值的调用f(r)
可以工作,但对下一行中的r值版本的调用不能.
很明显,当程序员强制执行特定的ArrayList<MyInt>
时,编译器中发生的约束求解过程是愉快的,但当我们通过将collect
的结果直接传递给f
来要求它端到端进行约束求解时,编译器将发送如下错误:
java: incompatible types: inferred type does not conform to upper bound(s)
inferred: java.lang.Object&java.util.List<? extends org.example.Main.MyInt>&java.util.Collection<org.example.Main.MyNum>
upper bound(s): java.util.Collection<org.example.Main.MyNum>,java.util.List<? extends org.example.Main.MyInt>,java.lang.Object
推断的上限与上限之间的唯一区别(从错误消息):
-
&
对,
的用法 - 对象的顺序(反转)
我假设顺序并不重要(它们是集合),&
和,
具有特殊的意义.
有人对正在发生的事情有更彻底的、不那么"挥手"的解释吗?