foreach - How does the Java 'for each' loop work? -
consider:
list<string> somelist = new arraylist<string>(); // add "monkey", "donkey", "skeleton key" somelist
for (string item : somelist) { system.out.println(item); }
what equivalent for
loop without using for each syntax?
for (iterator<string> = somelist.iterator(); i.hasnext();) { string item = i.next(); system.out.println(item); }
note if need use i.remove();
in loop, or access actual iterator in way, cannot use for ( : )
idiom, since actual iterator merely inferred.
as noted denis bueno, code works object implements iterable
interface.
also, if right-hand side of for (:)
idiom array
rather iterable
object, internal code uses int index counter , checks against array.length
instead. see java language specification.
Comments
Post a Comment