且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 8中的::(双冒号)运算符

更新时间:2022-05-13 03:30:20

通常,可以使用 Math.max(int,int)来调用 reduce 方法如下:

Usually, one would call the reduce method using Math.max(int, int) as follows:

reduce(new IntBinaryOperator() {
    int applyAsInt(int left, int right) {
        return Math.max(left, right);
    }
});

这需要很多语法才能调用 Math.max 。这就是lambda表达式发挥作用的地方。从Java 8开始,允许以更短的方式执行相同的操作:

That requires a lot of syntax for just calling Math.max. That's where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way:

reduce((int left, int right) -> Math.max(left, right));

这是如何工作的? java编译器检测,您要实现一个接受两个 int 的方法,并返回一个 int 。这相当于接口 IntBinaryOperator 的唯一方法的形式参数(方法的参数 reduce 你想要的打电话)。因此,编译器会为您完成其余的工作 - 它只是假设您要实现 IntBinaryOperator

How does this work? The java compiler "detects", that you want to implement a method that accepts two ints and returns one int. This is equivalent to the formal parameters of the one and only method of interface IntBinaryOperator (the parameter of method reduce you want to call). So the compiler does the rest for you - it just assumes you want to implement IntBinaryOperator.

但是作为 Math.max(int,int)本身满足 IntBinaryOperator 的形式要求,可以直接使用。因为Java 7没有任何允许方法本身作为参数传递的语法(您只能传递方法结果,但从不传递方法引用),所以 :: 语法在Java 8中引入了引用方法:

But as Math.max(int, int) itself fulfills the formal requirements of IntBinaryOperator, it can be used directly. Because Java 7 does not have any syntax that allows a method itself to be passed as an argument (you can only pass method results, but never method references), the :: syntax was introduced in Java 8 to reference methods:

reduce(Math::max);

请注意,这将由编译器解释,而不是由运行时的JVM解释!虽然它为所有三个代码片段生成不同的字节码,但它们在语义上是相等的,因此最后两个可以被认为是 IntBinaryOperator 实现的短(并且可能更有效)版本以上!

Note that this will be interpreted by the compiler, not by the JVM at runtime! Although it produces different bytecodes for all three code snippets, they are semantically equal, so the last two can be considered to be short (and probably more efficient) versions of the IntBinaryOperator implementation above!

(另见 Lambda表达式的翻译