0

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?

mehdi lotfi
  • 11,194
  • 18
  • 82
  • 128
matthias
  • 1,938
  • 23
  • 51

4 Answers4

7

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");
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It prints "a b c " because you are not changing(adding) anything in the list.

for (String s : strings) { s = new String("x"); }

The above code can be read as :

For each String s in List strings set s to a new String value "x". You are not doing anything to the list. You get the value from the list, store it in s and overwrite s.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

You only change the value of the local s variable, not the elements in the List.

You can change elements in the list by List.set(int index, E element).

icza
  • 389,944
  • 63
  • 907
  • 827
1

s you specified here has scope only in the for loop

 for (String s : strings) {
                s = new String("x");
            }

value of new String object is passed to s on each iteration, but strings is not getting affected at all.

nobalG
  • 4,544
  • 3
  • 34
  • 72