Does the Java for each loop return a reference, or a reference copy?
I know that Java doesn't really use exact pass by reference, but rather pass by reference copy. This is why a swap function that just tried to swap references wouldn't work in Java. Does a for-each loop do this as well?开发者_C百科 For instance, given the following code...
for (Constraint c : getLeafNodes(constraintGraph)){
c = new Constraint();
}
...I want to go through a recursively defined tree-like structure, and find all leaf nodes. Each leaf node needs to be replaced with a new, empty node. Will this do what I expect it to, or will it simply set a copy of the reference to each leaf node to a new node?
I wrote a similar method on another piece of code that passed unit tests, which makes me think a for-each loop uses references, not reference copy, but our code quality software flagged this as a dead-store to a local variable, major error.
Thanks.
It won't do either. That's similar to saying
Object c = getObject();
c = new Object();
All you've done is change what c
refers to. This wouldn't work even if Java supported true pass-by-reference
Short answer: reference-copy
When you assign an iterator's variable, it will not be propagated to the collection. See the iterator as a read-only access to the list.
Java's for loop works exactly as C#'s for-each
loop, in which while
the Enumerator
can moveNext
it will assign to the local variable the Current
element
No it will not do what you expect. c
is a local variable which refers/points to an element in the collection returned by getLeafNodes
. Java does not have the reference concept you mention, everything is a reference copy. If you know e.g. C or C++, think of object variables in java as pointers not references.
精彩评论