Date: 14 Oct 2021
To implement iteration in a collection
-
Include the following import statement so that our code can refer to Java’s
java.util.Iterator
interface:import java.util.Iterator;
-
Add the following to the class declaration, a promise to provide an
iterator()
method, as specified in thejava.util.Iterable
interface:implements Iterable
e.g public class Bag
implements Iterable { } -
Implement a method
iterator()
that returns an object from a class that implements theIterator
interface:public Iterator
- iterator() { return new LinkedIterator(); }
-
Implement a nested class that implements the
Iterator
interface by including the methodshasNext()
,next()
, andremove()
.