Accessing
a Collection via an Iterator
Often, you will want to cycle
through the elements in a collection. For example, you might want to display
each element. One way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. Iterator
enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional
traversal of a list, and the modification of elements. Iterator and ListIterator are
generic interfaces which are declared as shown here:
interface Iterator<E>
interface ListIterator<E>
Here, E
specifies the type of objects being iterated. The Iterator interface declares the methods shown in Table 18-8. The
methods declared by ListIterator
(along with those inherited from Iterator)
are shown in Table 18-9. In both cases, operations that modify the underlying
collection are optional. For example, remove(
) will throw UnsupportedOperationException
when used with a read-only collection. Various other exceptions are possible.
Using
an Iterator
Before you can access a
collection through an iterator, you must obtain one. Each of the collection
classes provides an iterator( )
method that returns an iterator to the start of the collection. By using this
iterator object, you can access each element in the collection, one element at
a time. In general, to use an iterator to cycle through the contents of a
collection, follow these steps:
Obtain an iterator to the start of the collection by calling the
collection’s iterator( ) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
Within the loop, obtain each element by calling
next( ).
For collections that
implement List, you can also obtain
an iterator by calling listIterator( ).
As explained, a list iterator gives you the ability to access the collection in either the forward or backward
direction and lets you modify an element. Otherwise,
ListIterator is used just like Iterator.
The following example
implements these steps, demonstrating both the Iterator and ListIterator interfaces.
It uses an ArrayList object, but the
general principles apply to any type
of collection. Of course, ListIterator
is available only to those collections that implement the List interface.
// Demonstrate iterators. import java.util.*;
class IteratorDemo {
public static void main(String args[]) { //
Create an array list.
ArrayList<String> al = new
ArrayList<String>();
//Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
//Use iterator to display contents of al.
System.out.print("Original contents of al:
");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
Modify objects being iterated.
ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) {
String element = litr.next(); litr.set(element
+ "+");
}
System.out.print("Modified contents of al:
"); itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards.
System.out.print("Modified list backwards:
");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
The output is shown here:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
Pay special attention to how the list is
displayed in reverse. After the list is modified, litr points to the end of the list. (Remember, litr.hasNext( ) returns false
when the end of the list has been reached.) To traverse the list in reverse,
the program continues to use litr,
but this time it checks to see whether it has a previous element. As long as it
does, that element is obtained and displayed.
The
For-Each Alternative to Iterators
If you won’t be modifying the
contents of a collection or obtaining elements in reverse order, then the
for-each version of the for loop is
often a more convenient alternative to cycling through a collection than is
using an iterator. Recall that the for
can cycle through any collection of objects that implement the Iterable interface. Because all of the
collection classes implement this interface, they can all be operated upon by
the for.
The following example uses a for loop to sum the contents of a
collection:
// Use the for-each for loop to cycle through a
collection.
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
//Create an array list for integers.
ArrayList<Integer> vals = new
ArrayList<Integer>();
//Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Contents of vals: ");
for(int v : vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0; for(int v : vals)
sum += v;
System.out.println("Sum of values: "
+ sum);
}
}
The output from the program
is shown here:
Contents of vals: 1 2 3 4 5
Sum of values: 15
As you can see, the for loop is substantially shorter and
simpler to use than the iterator-based approach. However, it can only be used
to cycle through a collection in the forward direction, and you can’t modify
the contents of the collection.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2026 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.