N.N.
N.N.

Reputation: 8502

Is there a Java equivalent of a for-each loop with a reference variable?

In C++ one can use reference variables in for-each statements, e.g. for (int &e : vec) where &e is a reference to the value of e. This enables one to change the value of the elements one interacts with in a for-each loop. Is there an equivalent construct in Java?

Here is an example of how a reference variable is used in a for-each loop in C++.

#include <iostream>
#include <vector>

int main()
{
    // Declare a vector with 10 elements and initialize their value to 0
    std::vector<int> vec (10, 0); 

    // e is a reference to the value of the current index of vec
    for (int &e : vec)
        e = 1;

    // e is a copy of the value of the current index of vec
    for (int e : vec)
        std::cout << e << " ";

    return 0;
}

If the reference operator, &, were not used in the first loop the assignment to 1 would only be to a variable e that is a copy (and not a reference) of the current element of vec, i.e. & enables one to not only read from a vector but also write to a vector in a for-each loop.

For example the following Java code does not modify the original array but merely a copy:

public class test {

    public static void main(String[] args) {
    test Test = new test();

    int[] arr = new int[10];

    for (int e : arr)   // Does not write to arr
        e = 1;

    for(int e : arr)
        System.out.print(e + " ");
    }
}

Upvotes: 1

Views: 4167

Answers (3)

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

In Java, objects are passed by reference and all other types are passed by value.

In other words, there is no way to modify e in your loop, since it's an int (ie you're writing to a value copy)

If you're looping over a collection of objects though, there is nothing stopping you from modifying them, as long as they expose the methods needed to modify them. You're still restricted to changing their value, not their reference (ie you can modify the object itself, but not change it to another object)

Upvotes: 2

NCH
NCH

Reputation: 111

There is no reference like in C++ in java.

If you want to modify a list object, you have to process the vector the old fashioned way:

for (int = 0; i < vector.size(); i++) {
Object oldObject = vector.get(i);
vector.set(i, newObject);
}

But if you want to modify the object content, a foreach would do the trick:

for (SomeObject o : list) {
o.setName("foo");
}

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

No, there isn't. And anyway, most of the collections throw a ConcurrentModificationException if you modify them while iterating on them.

Nothing forbids you to modify the object contained in the collection, though:

for (Customer c : customers) {
    c.setActive(false);
}

For lists, you can use a ListIterator to replace the current element while iterating. See http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html

Upvotes: 4

Related Questions