为什么Java 8引入* Integer.sum(int a,int b)* [英] Why did Java 8 introduce *Integer.sum(int a, int b)*

查看:2148
本文介绍了为什么Java 8引入* Integer.sum(int a,int b)*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚注意到JDK8为 Integer 类引入了此方法:

I just noticed that JDK8 introduced this method for Integer class:

 /**
 * Adds two integers together as per the + operator.
 *
 * @param a the first operand
 * @param b the second operand
 * @return the sum of {@code a} and {@code b}
 * @see java.util.function.BinaryOperator
 * @since 1.8
 */
public static int sum(int a, int b) {
    return a + b;
}

这种方法有什么意义?为什么我应该调用此方法而不是使用 + 运算符?我能想到的唯一可能性是,例如,当混合字符串和整数时, + 运算符会改变含义,所以

What's the point of this method? Why should i call this method instead of using the + operator? The only possibility I can think of is that, for instance, when mixing strings and ints the + operator changes meaning, so

System.out.println("1"+2+3); // prints 123
System.out.println("1"+Integer.sum(2,3)); // prints 15

但是使用括号仍可以使用

but using parenthesis would work anyway

System.out.println("1"+(2+3)); // prints 15


推荐答案

它可以作为一种方法很有用传递给需要相关功能接口的方法( IntBinaryOperator )。

It can be useful as a method reference (Integer::sum) passed to a method that requires a relevant functional interface (IntBinaryOperator).

例如:

int sum = IntStream.range(1,500).reduce(0,Integer::sum);

当然,这个例子可以使用 .sum()而不是减少。我刚注意到的Javadoc IntStream.sum 提到这个精确的减少等同于sum()。

Of course, this example can use .sum() instead of reduce. I just noticed that the Javadoc for IntStream.sum mention this exact reduction as being equivalent to sum().

这篇关于为什么Java 8引入* Integer.sum(int a,int b)*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆