简体   繁体   English

为什么在Eclipse中使用类型推理编译的这个java 8示例?

[英]Why didn't this java 8 example using type inference compile in Eclipse?

I am reading the newly released Java 8 in Action and found there is a piece of code pasted from Chapter 5 not compiling: 我正在阅读新发布的Java 8 in Action,发现第5章中有一段代码没有编译:

    List<Integer> numbers1 = Arrays.asList(1, 2, 3);
    List<Integer> numbers2 = Arrays.asList(3, 4);
    List<int[]> pairs =
    numbers1.stream()
    .flatMap((Integer i) -> numbers2.stream()
    .map(j -> new int[]{i, j})
    )
    .collect(toList());

Eclipse says: "Type mismatch: cannot convert from List<Object> to List<int[]> " Eclipse说:“类型不匹配:无法从List<Object>转换为List<int[]>

And after comparing with what the author gave on Github, the following compiled: 在与作者对Github的内容进行比较后,编译如下:

    List<Integer> numbers1 = Arrays.asList(1, 2, 3);
    List<Integer> numbers2 = Arrays.asList(3, 4);
    List<int[]> pairs =
    numbers1.stream()
    .flatMap((Integer i) -> numbers2.stream()
    .map((Integer j) -> new int[]{i, j})
    )
    .collect(toList());

The only change is from "j" to "(Integer j)". 唯一的变化是从“j”到“(整数j)”。

But isn't the first version completely equivalent to the second with the syntax sugar provided by Java 8? 但是第一个版本是不是完全等同于Java 8提供的语法糖的第二个版本? Why does Java refuse to compile it? 为什么Java拒绝编译它?

Thanks 谢谢

BTW: BTW:

java -version
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) Client VM (build 25.20-b23, mixed mode)

First, correcting your terminology: when you say syntax sugar , what you really are asking about is type inference , that when asked to infer a type for j in the inner lambda, that the compiler fails to come up with the right type. 首先,纠正你的术语:当你说语法糖时 ,你真正要问的是类型推断 ,当被要求推断内部lambda中j的类型时,编译器无法提出正确的类型。

Second, correcting your data: The error messages you cite are not coming from the JDK compiler; 第二,纠正您的数据:您引用的错误消息不是来自JDK编译器; they're coming from Eclipse. 他们来自Eclipse。

This is just an Eclipse bug. 这只是一个Eclipse bug。 The reference compiler ( javac from Oracle JDK) handles your first example just fine. 参考编译器(来自Oracle JDK的javac )处理你的第一个例子就好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM