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

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -