[英]Difference between BiFunction<X, X> and BinaryOperator<X>
我无法理解为什么BinaryOperator<Integer>
可以放在下面代码中的A
位置,而不是BiFunction<Integer, Integer>
?
A foo = (a, b) -> { return a * a + b * b; };
int bar = foo.apply(2, 3);
System.out.println(bar);
有人可以帮助我理解它。
BinaryOperator
是一个特殊的BiFunction
。 因此,您可以为它们分配相同的表达式。 看一下这个。
BinaryOperator<Integer> foo = (a, b) -> {
return a * a + b * b;
};
BiFunction<Integer, Integer, Integer> barFn = (a, b) -> {
return a * a + b * b;
};
如果你查看源代码,它会是
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
// Remainder omitted.
}
Bifunction 和 BinaryOperator 是相同的,但这里唯一的区别是接口的参数类型和返回类型。
考虑一种您想要连接两个字符串并返回结果的情况。 在这种情况下,您可以选择其中之一,但 BinaryOperator 是一个不错的选择,因为如果您关注参数和返回类型,它们都是相同的。
BinaryOperator<String> c=(str,str1)->str+str1;
你可以用 Bifunction 做同样的事情,但现在在这里看到不同之处:
BiFunction<String,String,String> c=(str,str1)->str+str1;
现在考虑我们想要将两个整数相加并返回一个字符串的情况。 这里我们只能选择 BiFunction 而不是 BinaryOperator:
BiFunction<Integer,Integer,String> c=(a,b)->"Answer="+(a+b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.