0

I am just wondering what does the highlighted part of the code do here?

public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
        throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i]; // what exactly does lastRet = i do??
}

does lastRet = i assigns i to lastRet? if so, if i = 3, then we have elementData[lastRet = 3]? but what does that do? I understand if I have elementData[0] then I am retrieving elementData at the 0 position, and if I have elementData[2] then I am retrieving elementData at the 3rd position. But what is elementData[lastRet = i]? is lastRet = i actually checking if lastRet equals to i? like lastRet == i? but if so, why not write lastRet ==i instead? so it shouldn't be checking equality. So what does lastRet = i do? so it assigns i to lastRet? But then I don't understand what the code: elementData[lastRet = i] do exactly?

2
  • It's setting lastRet and then evaluating it. Commented Dec 7, 2021 at 3:03
  • 1
    Adding ** to the code is confusing because it's no longer valid. It would be more clear if you removed the ** and just left the comment in the code. Commented Dec 7, 2021 at 3:08

1 Answer 1

1

The value of an assignment statement is the value being assigned.

In this case the value is just i but the statement also has the effect of storing that value in lastRet.

Sign up to request clarification or add additional context in comments.

3 Comments

so it has two operations in there? one is first assigning i to lastRet? and then take the operation of elementData[i] for whatever the value of i is? is it correct?
Yes. lastRet is assigned the value of i. The value of that expression is i which is used as the index to the array elementData. It is equivalent to lastRet = i; elementData[i]. Personally, I don't like the syntax elementData[ lastRet = i ]. I would prefer the long version because it is explicit and straightforward. Someone reading your code may have to stop and think for a moment about what elementData[ lastRet = i ] is actually doing. It's a speed bump to readability. Simple and straightforward is better. Use 2 lines to do this.
thank you for the explanations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.