Professional Documents
Culture Documents
Announcements: Iterators & Inner Classes
Announcements: Iterators & Inner Classes
Announcements: Iterators & Inner Classes
Lecture 15
CS211 Fall 2005
1
Iterator Interface Enumeration Interface
interface Iterator {
boolean hasNext();
Object next(); interface Enumeration {
void remove(); // Optional operation boolean hasMoreElements();
} Object nextElement();
}
interface Iterable {
Iterator iterator();
}
Predefined in Java
You may see some code that uses the Enumeration interface
java.util.Iterator
instead of the Iterator interface
java.util.Iterable Enumeration was part of the earliest versions of Java
Linear search can be written using Iterator interface Similar functionality to Iterator (no remove method)
Any class that wishes to allow linear searching can do so by Iterator is preferred
implementing Iterable (i.e., by providing an Iterator)
2
Iterator Features class Array2DIterator implements Iterator {
private Object[][] data;
private int rowIndex = 0, colIndex = 0;
3
class Shark implements Iterable {
Better: Iterator as an Inner Class public Object[] data;
public Shark(Object[] a) { data = a; }
public Iterator iterator()
Inner class: Java allows you declare a class within another Example {return new Remora();}
class of an class Remora implements Iterator {
private int index = 0;
Inner classes can occur at many levels within another class Inner public boolean hasNext()
{return (index < data.length);}
Member level Class public Object next()
Inner class defined as if it were another field or method
{return data[index++];}
Statement level public void remove()
Inner class defined as if it were a statement in a method {throw new UnsupportedOperationException();}
Expression level }
Inner class defined as it were part of an expression }
Such expression-level classes are called anonymous classes
4
Anonymous Class Example Anonymous-Class Properties
class Shark implements Iterable {
public Object[] data; An anonymous class is an inner class with the
public Shark(Object[] a) { data = a; }
public Iterator iterator() { usual class body, but
return new Iterator {
No class name
private int index = 0;
public boolean hasNext() No access specifier (i.e., no public/private/protected)
{return (index < data.length);}
public Object next() No constructor
{return data[index++];} No explicit use of extends or implements
public void remove()
{throw new UnsupportedOperationException();} It either extends one class or implements one interface
};
} new classOrInterfaceName {...body...}
}
Conclusions
Iterator interface allows one to write generic code
Works on data collections without regard to type of elements or
data structure