简体   繁体   English

Java8的IntSummaryStatistics编译错误

[英]Java8 compile error for IntSummaryStatistics

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;`

I came across this error in Java8 (in Eclipse Oxygen) : 我在Java8(在Eclipse Oxygen中)遇到了此错误:

List<Integer> nums = Arrays.asList(1,2,3);
IntSummaryStatistics stats2 = nums.stream().collect(Collectors.summarizingInt(x->x));`

System.out.println(stats2);// Works!

Now instead of using stats2, i directly pass the entire RHS to println: 现在,我不使用stats2,而是直接将整个RHS传递给println:

System.out.println(nums.stream().collect(Collectors.summarizingInt(x->x)));// Compile Error

Error: The method println(char) is ambiguous for the type PrintStream 错误:方法Println(char)对于类型PrintStream不明确

However, if I add a toString(), it works. 但是,如果我添加一个toString(),它将起作用。

System.out.println(nums.stream().collect(Collectors.summarizingInt(x->x)).toString());

So I am wondering why it's behaving like this! 所以我想知道为什么它会这样!

Generally when we pass an object to System.out.println() , it's toString() method would be called (internally). 通常,当我们将一个对象传递给System.out.println() ,将调用它的toString()方法(内部)。 So why do I need to explicitly call the toString() method? 那么,为什么需要显式调用toString()方法?

Also usually we can substitute the RHS to another method, like : 通常,我们也可以将RHS替换为另一种方法,例如:

double x = Math.sqrt(5);
System.out.println(x); // works
System.out.println(Math.sqrt(5)); //RHS substitution works

Any help in understanding this would be great. 了解这一点的任何帮助都将非常有用。

Added the exact code. 添加了确切的代码。

package java8.examples;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class SampleProblem {

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1,2,3);
        IntSummaryStatistics stats = nums.stream().collect(Collectors.summarizingInt(x->x));
        System.out.println(stats);
        System.out.println(nums.stream().collect(Collectors.summarizingInt(x->x))); //Produces compile error
    }

}

It looks like a Eclipse issue. 看起来像是Eclipse问题。 There is a open bug for Eclipse Oxygen warning this ambiguity in a method. Eclipse Oxygen有一个打开的错误,警告该方法存在这种歧义。 https://bugs.eclipse.org/bugs/show_bug.cgi?id=527083 https://bugs.eclipse.org/bugs/show_bug.cgi?id=527083

In your case, a workaround, it would be solved by casting: 在您的情况下,一种变通方法是通过强制转换解决:

System.out.println((IntSummaryStatistics)nums.stream().collect(Collectors.summarizingInt(x->x)));

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

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