• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Modifying a String inside an ArrayList<String>

 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see that we cannot modify the String which lies inside an ArrayList<String>.
Can someone tell me why ?

Here is some code that attempts to do this (the wrong way)-


Output-

 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because you can't change a String anywhere. They're immutable.

It doesn't matter whether it's in a List or not.

Your line s = s + " of steel!"; creates a new String and assigns it to s. The fact that the original reference pointed to a String you placed in a List is irrelevant.
 
justin smythhe
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Bear Bibeault wrote:Because you can't change a String anywhere. They're immutable.

It doesn't matter whether it's in a List or not.

Your line s = s + " of steel!"; creates a new String and assigns it to s. The fact that the original reference pointed to a String you placed in a List is irrelevant.



Thanks !
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic