Hello everyone, according to the idea, it was necessary to get a link to the object from the container method, change it by the link and make sure that it was changed, having received the link again. However, changing the value using the following method does not work.

SingleList<String> list = new SingleList<String>(); list.add("Hello"); String string = list.elementAt(0); string = string + ", world!"; System.out.println(list.elementAt(0)); 

But if you introduce an additional class, then everything works.

 class MyStr { public String str = new String(); MyStr(String str) { this.str = str; } } SingleList<MyStr> list = new SingleList<MyStr>(); list.add(new MyStr("Hello")); MyStr string = list.elementAt(0); string.str = string.str + ", world!"; System.out.println(list.elementAt(0).str); 

What is the fundamental difference between 1 and 2?

    1 answer 1

    The principal difference is that in the first case, the string object is immutable, unlike the second case.

    In Java, strings are immutable ( immutable ), and in this line:

     string = string + ", world!"; 

    when an attempt is made to change a string (in this case, during concatenation) a new object is created (other than the one in the list) and string already refers to this created new object.

    In the second case, you have objects of the type MyStr in the list and when the field value of this object changes, the MyStr string object MyStr string will not change and will refer to where it was previously referenced.