为什么 Java 8 引入 *Integer.sum(int a, int b)*
Why did Java 8 introduce *Integer.sum(int a, int b)*
刚刚注意到JDK8为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;
}
这个方法有什么意义?为什么我应该调用此方法而不是使用 +
运算符?我能想到的唯一可能性是,例如,当混合字符串和整数时, +
运算符会改变含义,因此
System.out.println("1"+2+3); // prints 123
System.out.println("1"+Integer.sum(2,3)); // prints 15
但无论如何使用括号都行得通
System.out.println("1"+(2+3)); // prints 15
它可以用作传递给需要相关功能接口 (IntBinaryOperator
) 的方法的方法引用 (Integer::sum
)。
例如:
int sum = IntStream.range(1,500).reduce(0,Integer::sum);
当然这个例子可以用.sum()
代替reduce。我刚刚注意到 IntStream.sum 的 Javadoc 提到这个精确的减少等同于 sum().
刚刚注意到JDK8为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;
}
这个方法有什么意义?为什么我应该调用此方法而不是使用 +
运算符?我能想到的唯一可能性是,例如,当混合字符串和整数时, +
运算符会改变含义,因此
System.out.println("1"+2+3); // prints 123
System.out.println("1"+Integer.sum(2,3)); // prints 15
但无论如何使用括号都行得通
System.out.println("1"+(2+3)); // prints 15
它可以用作传递给需要相关功能接口 (IntBinaryOperator
) 的方法的方法引用 (Integer::sum
)。
例如:
int sum = IntStream.range(1,500).reduce(0,Integer::sum);
当然这个例子可以用.sum()
代替reduce。我刚刚注意到 IntStream.sum 的 Javadoc 提到这个精确的减少等同于 sum().