List<String> list = new ArrayList<String>();
String string = null;
string = "123";
list.add(string);
string = "456";
list.add(string);
for (String s : list)
{
System.out.println(s);
}
This program outputs:
123
456
which is pretty natural.
However, I'm thinking in another way. "string" is the reference(pointer) to the actual String object. When executing add(), it just stores the reference. When "string" refers to another String object, why the list still keeps the original one? Does it make a copy before add()?
The "value" of a String variable is a reference to the (immutable) object that is the string.
So there is no copy of the String but a copy of the reference. Having this reference doesn't allow you to change the original variable (you have no link to it) and doesn't allow you to change the string as it is immutable.
What you have here, inside the array contained by the arrayList after the two calls to add, is two different references. They could point to the same string but changing one reference doesn't change the other one. If you wanted to change the first reference in this case to point to the same string as the second one, the simplest would have been to do list.set(0, list.get(1));
When "string" refers to another String object, why the list still keeps the original one?
What you've added to the list is the reference to the string. Later, when you do
string = "456";
you're not changing the existing string, you're assigning a reference to a different string to the string variable. The original string is unchanged (in fact, strings in Java are immutable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With