Java Reference
In-Depth Information
• The loop variable of the foreach loop must be declared as part of the loop, with
both a type and a variable name. You cannot use a variable declared outside the
loop as you can with the for loop.
To understand in detail how the foreach loop works with collections, we need to
consider two interfaces, java.util.Iterator and java.lang.Iterable :
public interface Iterator < E > {
boolean hasNext ();
E next ();
void remove ();
Iterator defines a way to iterate through the elements of a collection or other data
structure. It works like this: while there are more elements in the collection ( has
Next() returns true ), call next to obtain the next element of the collection. Ordered
collections, such as lists, typically have iterators that guarantee that they'll return
elements in order. Unordered collections like Set simply guarantee that repeated
calls to next() return all elements of the set without omissions or duplications but
do not specify an ordering.
The next() method of Iterator performs two functions—
it advances through the collection and also returns the old
head value of the collection. This combination of operations
can cause problems when programming in an immutable
style, as it fundamentally mutates the collection.
The Iterable interface was introduced to make the foreach loop work. A class
implements this interface in order to advertise that it is able to provide an Iterator
to anyone interested:
public interface Iterable < E > {
java . util . Iterator < E > iterator ();
If an object is Iterable<E> , that means that that it has an iterator() method that
returns an Iterator<E> , which has a next() method that returns an object of
type E .
Note that if you use the foreach loop with an Iterable<E> , the
loop variable must be of type E or a superclass or interface.
For example, to iterate through the elements of a List<String> , the variable must
be declared String or its superclass Object , or one of the interfaces it implements:
CharSequence , Comparable , or Serializable .
Search WWH ::

Custom Search