I'm under the impression that the variable in for-each loop would get the value copied from the elements from the array. E.g.:
String[] strs = new String[] {"a", "b"};
for (String s : strs) {
s = "c";
}
for (String s : strs) {
System.out.println(s);
}
The above code has nothing to do with the original array strs and thus the output is still:
a
b
This is expected as the variable s in the for-each loop is actually a copy of the element. However, if I define my own class along with assignment constructor, the behavior changes:
class Node {
public Node(Integer value, String str) {
value_ = new Integer(value.intValue());
str_ = new String(str.toCharArray());
}
public Node(Node node) {
this(node.value(), node.str());
}
public Integer value() { return value_; }
public String str() { return str_; }
public Integer value_ = 0;
public String str_ = "null";
}
Node[] my_list = new Node[] {new Node(1, "a"), new Node(2, "b")};
for (Node n : my_list) {
n.value_ = 3;
n.str_ = "c";
}
for (Node n : my_list) {
System.out.println(n.value() + " " + n.str());
}
The output now is:
3 c
3 c
which means the variable n in the for-each loop is not a copy of the element but a reference.
Anyone can help explains why the behavior of for-each loop on String and my own class Node is inconsistent?
Thanks!