views:

113

answers:

4

Say I have the following piece of java code

ArrayList<Double> myList = new Double[100];
for (Double x : myList)
    x = randomDouble();

Does this actually modify myList or just the dummy variable?

I realize I should just try this code segment out, but I think this is the sort of thing I should be able to google or search for on this site, and several queries so far have turned up nothing useful.

+9  A: 

It doesn't modify myList. It works by calling myList.iterator(), then (repeatedly) hasNext() and next(), none of which change myList.

Also, Java does not have C++-style references. That means you don't need to worry (even without looking at the API) about x being a reference that could modify myList.

Finally, that's invalid syntax. It should be:

ArrayList<Double> myList = new ArrayList<Double>(); 
/* or new ArrayList<Double>(100), but that's only an optimization 
(initial capacity), not the size. */
Matthew Flaschen
@Doug that should work.
msakr
A: 

It dos not change the value in the list.

You assign a new Double object to the reference x, which leaves the original object unchanged.

Simon Lehmann
No. There is no 'reference x'. Each loop iteration assigns the appropriate Double object to the *variable called x*. Assigning another value to the x variable has no effect upon the previous contents (excluding the case where assigning a new value may make the previous value eligible for reclamation).
pst
At least to me, variables and references are synonyms when it comes to objects (in Java). The x in the loop body is a reference to the current object processed by the loop. If you assign some other object to the reference, it does not change the original object (as you said "…has no effect upon the previous contents").
Simon Lehmann
+2  A: 

Does this actually modify myList or just the dummy variable?

Just the dummy variable.

BTW you code doesn't even compile.

It should be either:

ArrayList<Double> myList = new ArrayList<Double>(100);

or

Double[] myList = new Double[100];
OscarRyz
or of course, `double[] myList = new double[100];`
msakr
+1  A: 

So with the benefit of hindsight, the answer I was looking for would look something like this:

Using the "=" operator will set the object x to a new value without modifying any of the values in the variable myList. To modify myList using the foreach loop construct, one needs to access a modifier method for the object. For example:

for (MyDouble x : myList) {
    x.setX( randomDouble() );
}
Doug