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

I was exploring the Java 8 source and found this particular part of code very surprising:

//defined in IntPipeline.java

@Override

public final OptionalInt reduce(IntBinaryOperator op) {

return evaluate(ReduceOps.makeInt(op));

}

@Override

public final OptionalInt max() {

return reduce(Math::max); //this is the gotcha line

}

//defined in Math.java

public static int max(int a, int b) {

return (a >= b) ? a : b;

}

Is Math::max something like a method pointer? How does a normal static method get converted to IntBinaryOperator?

解决方案

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);

}

});

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));

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.

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);

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值