简体   繁体   中英

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<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). 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.

Also lets say num2.get(0) = -2 and num1.get(0) = -3 then if we evaluated for sign we'd get sign=-1. Because (-3< 0 ^ -2) AND (0 ^ -2 < 0)? -1:1; (-3< 0 ^ -2) AND (0 ^ -2 < 0)? -1:1; evaluates to -1.

But this would be wrong -3*-2 should be a positive number. 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

It isn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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