Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 444
rybosome Avatar asked May 02 '11 15:05

rybosome


People also ask

Does Java return by reference?

Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below.

Does Java have for-each loops?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.


1 Answers

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

like image 58
Chris Thompson Avatar answered Sep 27 '22 17:09

Chris Thompson