I have the following code
List<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("b");
strings.add("c");
for (String s : strings) {
s = new String("x");
}
System.err.println(strings);
which prints [a, b, c]
I thought it would print [x, x, x] because I iterate over the Strings, which returns a reference to a String Object. In the loop I assign a new Object to the reference, accordingly s should point to the new String Object?
Where is my fault?
What is the best way to update the strings in my array?
In the loop I assign a new Object to the reference
Well, you assign a new reference as the value for s
. s
is just a local variable though, which was initialized with the value of the element. It's not tied to the element in the list though - that was just how it was initialized. It's a bit like changing the value of a method parameter - that doesn't change whatever variable was used as an argument:
void method(String y) {
y = "bar"; // This doesn't change x.
}
...
String x = "foo";
method(x);
System.out.println(x); // foo
If you want to update the strings in your list (not an array - it's worth being clear about the difference) you should use a regular for
loop:
for (int i = 0; i < strings.size(); i++) {
strings.set(i, "x");
}
See more on this question at Stackoverflow