Java Reference
In-Depth Information
Ken
Lee
Joe
The Collections Framework supports fast-fail concurrent iterators. You can obtain multiple iterators for a
collection and all of them can be used to iterate over the same collection concurrently. If the collection is modified by
any means, except using the
remove()
method of the same iterator after the iterator is obtained, the attempt to access
the next element using the iterator will throw a
ConcurrentModificationException
. It means that you can have
multiple iterators for a collection; however, all iterators must be accessing (reading) elements of the collection. If any
of the iterators modify the collection using its
remove()
method, the iterator that modifies the collection will be fine
and all other iterators will fail. If the collection is modified outside of all iterators, all iterators will fail.
■
an
Iterator
is a one-time object. You cannot reset an iterator. it cannot be reused to iterate over the element of
the collection. if you need to iterate over the elements of the same collection again, you need to obtain a new
Iterator
calling the
iterator()
method of the collection.
Tip
Using a for-each Loop
You can use the for-each loop to iterate over elements of a collection that hides the logic to set up an iterator for a
collection. The general syntax for the for-each loop is as follows:
Collection<T> yourCollection = // get a collection here;
for(T element : yourCollection) {
/* The body of the for-each loop is executed once for each element in yourCollection.
Each time the body code is executed, the element variable holds the reference of the
current element in the collection
*/
}
■
You can use the for-each loop to iterate over any collection whose implementation class implements the
Iterable
interface. the
Collection
interface inherits from the
Iterable
interface, and therefore, you can use the for-each
loop with all types of collections that implement the
Collection
interface. For example, the
Map
collection type does not
inherit from the
Collection
interface, and therefore, you cannot use the for-each loop to iterate over entries in a
Map
.
Tip
The for-each loop is simple and compact. Behind the scenes, it gets the iterator for your collection and calls the
hasNext()
and
next()
methods for you. You can iterate over all elements of a list of string as follows:
List<String> names = // get a list;
// Print all elements of the names list using a for-each loop
for(String name : names) {
System.out.println(name);
}