dasLort
dasLort

Reputation: 1294

Change the reference in a Java List

I somehow feel stupid to ask this question, BUT

Why is it not possible to change the reference to an object in a List by hand using the EnhancedForStatement?

private static List<String> list = new ArrayList<String>();

public static void main(String[] args) {
    list.add("AAA");
    list.add("BBB");
    list.add("CCC");

    for(String s : list){
        if(s.equals("BBB")) s = "QQQ";
    }

    System.out.println(list);
}

Will print [AAA, BBB, CCC] because the reference to the second element wasn't changed, as one could expect.

But why am I not allowed (or is List the wrong type?) to manually change the reference of the list entry? String in this example could be any complex type, this question is about the changing of references in a List.

edit: OK, maybe it is clear why it works the way it works, but how can I accomplish the reference change? I can't believe there is no way for any subtype of List to change the reference of any element.

edit2: so it is not possible to change the reference when using the EnhancedForStatement?

Upvotes: 1

Views: 563

Answers (3)

mirvine
mirvine

Reputation: 126

You could make a temporary list.

private static List<String> list = new ArrayList<String>();

public static void main(String[] args) {
    list.add("AAA");
    list.add("BBB");
    list.add("CCC");

    List<String> templist = new ArrayList<String>();   

    for(String s : list){
       if(s.equals("BBB")) s = "QQQ";

       templist.add(s);
    }
    list = templist;

    System.out.println(list);
}

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Let's dig a bit into how the enhanced for loop works on the background.

for (String s : list) { .. }

is actually translated to:

for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
    String s = iter.next();
    ..
    s = "QQQ";
}

As you can see, passing a new reference to the s variable, just changes it for the scope of the loop, which doesn't have any effect on the list entry.

If you need to modify the current element that's being handled by the iterator, working with ListIterator makes it very easy:

for (ListIterator<String> iter = list.listIterator(); iter.hasNext();) {
    String s = iter.next();
    ..
    iter.set("QQQ");
}

Note that before iter.set(...), we need to call iter.next().

Upvotes: 5

Eran
Eran

Reputation: 393781

s is a String variable, and assigning to it doesn't affect the list.

In order to change the list, call list.set(1,"QQQ");, which would put a new String as the second element of the list.

Upvotes: 5

Related Questions