Consider:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for loop look like without using the for each syntax?
Best Solution
Note that if you need to use
i.remove();in your loop, or access the actual iterator in some way, you cannot use thefor ( : )idiom, since the actual iterator is merely inferred.As was noted by Denis Bueno, this code works for any object that implements the
Iterableinterface.Also, if the right-hand side of the
for (:)idiom is anarrayrather than anIterableobject, the internal code uses an int index counter and checks againstarray.lengthinstead. See the Java Language Specification.