Java Reference
In-Depth Information
return fl;
}
}
The
get()
method in the
FireworkList
class relieves clients from having to cast its
return value. To complete this thought, it is useful to provide an iterator that also relieves
clients from casting and from getting a possible
ClassCastException
. The
Itr
class is
useful only to the
FireworkList
class, so it is a good idea to make it an inner class:
package com.oozinoz.fireworks;
import java.util.*;
public class FireworkList
{
protected List list = new ArrayList();
public class Itr
{
private Iterator iterator = list.iterator();
public boolean hasNext()
{
return iterator.hasNext();
}
public Firework next()
{
return (Firework) iterator.next();
}
}
public void add(Firework f)
{
list.add(f);
}
public Firework get(int index)
{
return (Firework) list.get(index);
}
public FireworkList.Itr iterator()
{
return new Itr();
}
public int size()
{
return list.size();
}
}
Note that the
Itr
class does not implement the
Iterator
interface from the
java.util
package. The
Iterator
interface requires a
remove()
method that is not appropriate in
this code. By not implementing any interface, however, the code requires clients to refer to
the iterator's type with the type
Firework.Itr
.
A client can iterate over a
FireworkList
collection without having to cast its results: