简体   繁体   English

Java表达式的求值顺序

[英]Order of evaluation of java expression

So I have to arraylists which represent integers for example num1 = <-1,4,5> would represent -145 and num2= <2,3,6> would represent 236. 因此,我必须使用代表整数的arraylist,例如num1 = <-1,4,5>将代表-145, num2= <2,3,6>将代表236。

ArrayList<Integer> num1 = new ArrayList<>(Arrays.asList(1,2,9));
ArrayList<Integer> num2 = new ArrayList<>(Arrays.asList(-5,5));
final int sign = num1.get(0) < 0 ^ num2.get(0) < 0 ? -1 : 1;

So sign is supposed to determine the sign that would occur from multiplying num1 with num2 ( -145*236 would be a negative number). 因此,应该以正负号来确定将num1与num2相乘会产生的正负号( -145*236为负数)。 So comparison operators are non associative so this should be an equivalent expression: 因此比较运算符是非关联的,因此它应该是一个等效表达式:

sign = (num1.get(0) < 0 ^ num2.get(0)) && (0 ^ num2.get(0) < 0) ? -1:1;

Whats confusing me is why is num2.get(0) being XOR'ed with 0 because that does not alter num2.get(0) at all. 令我困惑的是为什么将num2.get(0)与0进行异或运算,因为这根本不会改变num2.get(0)

Also lets say num2.get(0) = -2 and num1.get(0) = -3 then if we evaluated for sign we'd get sign=-1. 还可以说num2.get(0) = -2num1.get(0) = -3那么如果我们评估符号,我们将得到sign = -1。 Because (-3< 0 ^ -2) AND (0 ^ -2 < 0)? -1:1; 因为(-3< 0 ^ -2) AND (0 ^ -2 < 0)? -1:1; (-3< 0 ^ -2) AND (0 ^ -2 < 0)? -1:1; evaluates to -1. 得出-1。

But this would be wrong -3*-2 should be a positive number. 但这是错误的-3 * -2应该是一个正数。 So what am I missing because I know this code is correct (it's from a textbook). 所以我缺少了什么,因为我知道这段代码是正确的(来自教科书)。

num1.get(0) < 0 ^ num2.get(0) < 0 ? -1 : 1

is evaluated as 被评估为

((num1.get(0) < 0) ^ (num2.get(0) < 0)) ? -1 : 1

This is determined by operator precedence. 这由运算符优先级确定。 Comparison operators being non-associative has nothing to do with it whatsoever. 非关联的比较运算符与它无关。

Whats confusing me is why is num2.get(0) being XOR'ed with 0 令我困惑的是为什么num2.get(0)与0进行异或

It isn't. 不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM