• Post Reply Bookmark Topic Watch Topic
  • New Topic

Modifying a String inside an ArrayList<String>  RSS feed

 
justin smythhe
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • 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-

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
  • 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 !
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!