这更多的是理解
Java对算术运算的评估的理论问题.由于和 – 具有相同的优先级,我不太明白Java如何评估以下表达式(两个操作数之间有多个操作符).
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(a+-b); // results in -1
System.out.println(a-+b); // results in -1
System.out.println(a+-+b); // results in -1
System.out.println(a-+-b); // results in 3
System.out.println(a-+-+b); // results in 3
System.out.println(a+-+-b); // results in 3
System.out.println(a-+-+-b); // results in -1
System.out.println(a+-+-+b); // results in 3
}
从Java 8语言规范(§15.8.2):
The binary + operator performs addition when applied to two operands of numeric type,producing the sum of the operands.
The binary – operator performs subtraction,producing the difference of two numeric operands.
[…]
Addition is a commutative operation if the operand expressions have no side effects.
Integer addition is associative when the operands are all of the same type.
我也注意到,每次#perators是偶数,结果是一样的,顺序并不重要.
但是当#operators是奇数时,这并不一定会影响结果.例如.在以下两个表达式中还有一个 – 但结果不同.
System.out.println(a-+-b); // results in 3
System.out.println(a-+-+-b); // results in -1
有了所有这些信息,我仍然看不到这种模式或这种方式如何运作.