• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Lambda Expressions explanation please

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Code:

The expression x->x=x+1; doesn't actually change the elements in the list.

Why does following code changes the objects in list: (assume Student have two fields name and age and properly getter/setter and overriden toString method )
 
Marshal
Posts: 80763
488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
reply
    Bookmark Topic Watch Topic
  • New Topic