-2

last = cur = cur == null ? head : cur.link;

I am trying to understand this using if and else statement. But I am stuck on this one. Can anyone help this out

1 Answers1

5

Your expression is equal to

if (cur == null) {
    cur = head;
} else {
    cur = cur.link;
}
last = cur;

You can split the example into two parts for easier understanding. Part 1:

last = cur = xxx;

is the same as

cur = xxx;
last = cur;

Part 2:

cur = cur == null ? head : cur.link;

is the same as

if (cur == null) {
    cur = head;
} else {
    cur = cur.link;
}

And part 2 would be even easier to understand if cur didn't appear three times. So this is simpler:

a = b == null ? c : d;

is the same as

if (b == null) {
    a = c;
} else {
    a = d;
}
Stefan
  • 2,395
  • 4
  • 15
  • 32
  • 1
    `last = cur = xxx;` is only the same as `last = xxx; cur = xxx;` if `xxx` has no side-effects and evaluates to the same thing every time (which is not the case for `last = cur = cur + 1` or `last = cur = myList.add(1)` for example). It's always the same as `cur = xxx; last = cur;`, which you used in your rewrite of the example one-liner. – Raniz Oct 20 '17 at 06:51
  • 1
    @Raniz, I stand corrected. Thanks.I've now updated the answer. – Stefan Oct 20 '17 at 06:53