matthias
matthias

Reputation: 2062

Java references not updated

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?

Upvotes: 0

Views: 221

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1502786

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");
}

Upvotes: 7

nobalG
nobalG

Reputation: 4630

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.

Upvotes: 1

icza
icza

Reputation: 418377

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).

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

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.

Upvotes: 1

Related Questions