An Iterator is
an object that enables you to navigate through a collection and to remove
elements from the collection selectively, if desired. You get an Iterator for
a collection by calling its iterator method. The following is
the Iterator interface.
public
interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
The hasNext() method returns true if the iteration has more elements, and the next() method returns the
next element in the iteration.
The remove() method removes the
last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.
[Note: Iterator.remove is the only safe way to modify a collection
during iteration; the behavior is unspecified if the underlying collection is
modified in any other way while the iteration is in progress.]
Use Iterator instead of
the for-each :
- Remove
the current element. The for-each construct
hides the iterator, so you cannot call remove. Therefore, the for-each construct
is not usable for filtering.
- Iterate
over multiple collections in parallel.
The following method shows you how to use
an Iterator to filter an arbitrary Collection — that is,
traverse the collection removing specific elements.
public static void main(String args[]) {
List<String> list = new ArrayList<>(Arrays.asList("a",
"b", "c", "d"));
for (Iterator<String> iter =
list.iterator(); iter.hasNext();) {
if (iter.next().equals("c")) {
iter.remove();
}
}
System.out.println(list);
}
Output:
[a, b, d]
A brief example:
public class Test_Iterator {
public static void main(String
args[]) {
// Create an array list
ArrayList al = new
ArrayList();
// 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 itr =
al.iterator();
while (itr.hasNext())
{
//------hasNext()---------
Object element =
itr.next();
//-------next()---------
System.out.print(element + " ");
}
}
Output: Original contents of al: C A E B D F
Comments
Post a Comment