java - Why a string variable does not change when modified inside a function but a List does -


imagine situation:

you have string, , called funtion recieves string parameter , change value inside funtion. string value outside function not change, change inside function.

but if same list<string> list<string> content modified outside function.

why happen?

look code repo:

using system; using system.collections.generic;  class program {     static void main()     {         list<string> list = new list<string>();         list.add("1");         string text = "text";         changesomethingintext(text);         console.writeline(text);         changesomethinginlist(list);         foreach (var in list)         {             console.writeline(i);         }     }       public static void changesomethingintext(string text)     {         text = "text changed";     }      public static void changesomethinginlist(list<string> mylist)     {          mylist.add("from change");     } } 

this result: text still "text", list has new element.

enter image description here

i tested in c# string vs list , in java string vs arraylist same behavior.

you have string , called function receives string parameter , change value inside function.

technically, can't change value of string, because strings immutable. have no way change them. can create new string , change variable points new string.

this text = "new value"; does. creates entirely new string object , changes variable text points new string. original string still in memory somewhere, , other variables point still point it.

which why:

the string value outside function not change, change inside function.

because when called function, passed copy of reference called text. inside function, changed function's copy of reference point other string, outside reference unaffected.

but if same list<string> list<string> content modified outside function.

nope, if assign new value reference list<string>, change happens inside function.

mylist = new list<string>() { "new list" }; 

you won't see change outside function.

what doing mutating existing list:

mylist.add("new item"); 

this can't string. there no functions on string class let modify string in place. if there were, changes would visible outside function.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -