我不明白为什么以下程序无法编译:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
System.out.println(new ArrayList<Integer>(Arrays.asList(1, 2)).stream().map((Integer s) -> {
return "" + (s * s);
}).collect(Collectors.toCollection(ArrayList<String>::new)));
}
}
而下面的代码编译得很干净,唯一的区别是我提取了 println
转换为一个变量(其类型甚至由编译器来推断)。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
var r = new ArrayList<Integer>(Arrays.asList(1, 2)).stream().map((Integer s) -> {
return "" + (s * s);
}).collect(Collectors.toCollection(ArrayList<String>::new));
System.out.println(r);
}
}
对于第一个,javac(16.0.1)报告:
$ javac -Xdiags:verbose Main.java
Main.java:8: error: method println in class PrintStream cannot be applied to given types;
System.out.println(new ArrayList<Integer>(Arrays.asList(1, 2)).stream().map((Integer s) -> {
^
required: String
found: ArrayList<String>
reason: argument mismatch; inference variable R has incompatible bounds
lower bounds: String,Collection<T#2>,Object
lower bounds: ArrayList<String>
where R,A,T#1,T#2,C are type-variables:
R extends Object declared in method <R,A>collect(Collector<? super T#1,A,R>)
A extends Object declared in method <R,A>collect(Collector<? super T#1,A,R>)
T#1 extends Object declared in interface Stream
T#2 extends Object declared in method <T#2,C>toCollection(Supplier<C>)
C extends Collection<T#2> declared in method <T#2,C>toCollection(Supplier<C>)
1 error
由于我不是一名java程序员,我无法判断我是否面临编译器错误,或者java类型系统的真正限制,我不理解。在后一种情况下,请向我提供适当的文档。
提前谢谢。
暂无答案!
目前还没有任何答案,快来回答吧!