Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the for foreach construct in java create a hard or soft copy?

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.

like image 644
Doug Avatar asked Sep 14 '26 10:09

Doug


1 Answers

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. */
like image 173
Matthew Flaschen Avatar answered Sep 16 '26 22:09

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!