Added to our λs forum.
Alexander Zotz wrote:. . . x->x=x+1; doesn't actually change the elements in the list.
No. If you look at
ArrayList#forEach(), you find it is defined
elsewhere, and it passes a copy of the result got from the Iterator to the Consumer. That Consumer consumes what has been passed; all it does is replace it with a new value. Just as in any other pass by value situation, the assignments
are not reflected back to the original source.
This link says that
forEach() behaves just like an
enhanced for loop, also called a
for‑each loop (hence the name
forEach()), and a
for‑each loop does not pass assignments back to its source.
Why does following code changes the objects in list . . .
It does not change the objects in the List. Because your List contains mutable objects, it is possible to change those objects'
state (i.e. the age field) without changing which objects are in the List.