我只是注意到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)