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?