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 + " ");
}
}
In Java, objects are passed by reference and all other types are passed by value.
In other words, there is no way to modify
ein your loop, since it’s anint(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)