Java foreach using reference to replace items won't work -
in exercice must replace object within loop. solution use "listiterator". colleague try use foreach syntax , play reference solution won't work.
// doesn't work ( growable growable : growables ) { growable = growable.grow(); // return object (seed -> sprout, ..) } // (final listiterator<growable> = growables.listiterator(); it.hasnext();) { it.set(it.next().grow()); }
from documentation[1], can read foreach not suitable replacement because don't have reference iterator.
the program needs access iterator in order remove current element. for-each loop hides iterator, cannot call remove. therefore, for-each loop not usable filtering. not usable loops need replace elements in list or array traverse it.
but have reference iterated object. wrong ? can explain me why "foreach" solution isn't working ?
thanks
[1] http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
in first snippet, take element growables
, assign growable
. means variable growable
references element.
if reassign growable
, starts referencing object. doesn't change object growables
.
to understand what's going on, compare array. using foreach syntax:
int[] array = {1, 2, 3}; (int x : array) { x = 0; } system.out.println(array[0]);
this print 1
. reason snippet equivalent to
int[] array = {1, 2, 3}; (int = 0; < array.length; i++) { int x = array[i]; x = 0; } system.out.println(array[0]);
now it's more obvious assignment x
not modify array
.
Comments
Post a Comment