Saturday 3 August 2013

36:Traversing Collections

Learning Objectives
After completing this session, you will be able to:
‰  Describe the two schemes ofTraversing Collections
‰  Define Iterator interface and Iterable Interface
‰  Apply Iterator
Two Schemes of Traversing Collections
The two schemes of traversing collections are:
‰  for-each:The for-each construct allows you to concisely traverse a collection or array
using a for loop
for (Object o: collection)
System.out.println(o);
‰  Iterator: An Iterator is an object that enablesyou to traverse through a collection and
to remove elements from the collection selectively, if desired.
Iterator Interface
public interface Iterator {
boolean hasNext();
Object next();
void remove(); //optional
}
‰  hasNext() method returns true if the iteration has more elements.
‰  next() method returns the next element in the iteration.
‰  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 Over for-each
‰  Iterator is used over for-each for removing 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.
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
‰  Iterating over multiple collections in parallel
The Iterable Interface
‰  Iterable is a generic interface that was added by Java 2, v5.0.
‰  The Iterable interface must be implemented byany class whose objects will be applied
by the for-each version of the for loop.
‰  In other words, a class must implement Iterable whenever an object needs to be used
within a for-each style for loop in that class.
‰  Iterable has the following declaration:
interface Iterable<T>
‰  It defines one method, iterator() , as shown here:
Iterator<T> iterator()
‰  It returns an iterator to the set of elements contained in the invoking object.
‰  Although the for-each form of the for loop was designed with arrays and collections in
mind, it can be used to cycle through the contents of any object that implements the
Iterable interface.
‰  This enables you to create classes whose objects can be applied with the for-each
form of the for loop.
‰  This is a powerful feature that substantially increases the types of programming
situations to which the for can be applied.
Try It Out
Problem Statement:
Write a program that illustrates the usage of List and an Iterator.
Code:
import java.util.*;
class Dog {
public String name;
Dog(String n) {
name = n;
}
}
class IteratorTest {
public static void main(String[] args) {
List<Dog> d = new ArrayList<Dog>();
Dog dog = new Dog("aiko");
d.add(dog);
d.add(new Dog("clover"));
d.add(new Dog("magnolia"));
Iterator<Dog> itr = d.iterator(); // make an iterator
while (itr.hasNext()) {
Dog d2 = itr.next(); // cast not required
System.out.println(d2.name);
}
How It Works:
‰  When you run IteratorTest, it displays the following results:
aiko
clover
magnolia
size 3
get1 clover
aiko 0
oa aiko
oa clover
‰  Firstly, you have used generics syntax to create the Iterator (an Iterator of type Dog).
‰  Because of this, when you have used the next() method, you did not have to cast the
object returned by next() to a Dog.
‰  You could have declared the Iterator like this (on using JDK1.4 or lesser version):
Iterator itr = d.iterator; // make an Iterator
‰  But then you would have had to cast the following returned value:
Dog d2 = (Dog)itr.next();
‰  The rest of the code demonstrates using the size() , get() , indexOf() , and toArray()
methods.
‰  Note:Invoking hasNext() does not move the iterator to the next element of the
collection.
Tips and Tricks:
Explain briefly about the ConcurrentModificationException related to Iterators.
Solution:
‰  ConcurrentModificationException exception (extends RuntimeException) may be
thrown by methods that have detected concurrent modification of a backing object
when such modification is not permissible.
‰  For example, it is not permissible for one thread to modify a Collection while another
thread is iterating over it. In general, the results are undefined under these
circumstances. Some Iterator implementations (including those of all the collection
implementations provided by the JDK) may choose to throw this exception if this
behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail
quickly and cleanly, rather that risking arbitrary behavior that is not deterministic at an
undetermined time in the future.
Summary
‰  Iterable is a generic interface that was added by Java 2, v5.0.
‰  Iterable contains only one method as shown below:
Iterator<T> iterator()
‰  The earlier method returns an Iterator to the elements contained in the invoking object.
‰  Because the iterator() method of Iterable returns an Iterator, often a class that
implements Iterable will also implement Iterator.
‰  Iterator is a generic class in Java 2, v5.0, when the entire Collections Framework was
retrofitted for generics.
‰  Earlier versions of Iterator were not generic.

No comments:

Post a Comment