为什么Java 8引入*Integer.sum(int a,int b)*

Lui*_*ese 19 java integer java-8

我只是注意到JDK8为Integer类引入了这个方法:

 /**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

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

System.out.println("1"+2+3); // prints 123
System.out.println("1"+Integer.sum(2,3)); // prints 15
Run Code Online (Sandbox Code Playgroud)

但无论如何,使用括号会起作用

System.out.println("1"+(2+3)); // prints 15
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 37

它可以作为Integer::sum传递给需要相关功能接口(IntBinaryOperator)的方法的方法reference ().

例如 :

int sum = IntStream.range(1,500).reduce(0,Integer::sum);
Run Code Online (Sandbox Code Playgroud)

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

  • 更有趣的问题是:“差”、“乘积”和“商”呢?(也许没有足够的“明显”用例。但是无论使用 `Integer::sum` 还是 `(a,b)->(a+b)` 也没有那么重要......) (2认同)