Look up the Iterator and Iterable interface in the Java 11 Class Library. What
are these interfaces' required methods?
You want your LibraryManager class to implement the
Iterator interface so that its Transaction
objects can be processed in a for loop. If manager is a
LibraryManager object that implements
Iterator,
we can do something like this:
for (LibraryItem item : manager) {
System.out.println(t);
}
Ans: The required method of the Iterable interface is
iterator. Since the TransactionManager interface
contains the ArrayList collection named col, we can use the iterator of the arraylist as our
TransactionManager class; we define our Transaction
iterator method like this:
@Override
public Iterable<Transaction> iterator( ) {
return col.iterator( );
}
The required methods of the Iterator interface are hasNext and
next. Instead of using the for loop above, which uses
the iterator behind the scenes (implicit iteration), we can use the iterator
methods explicitly like this:
Iterable<LibraryItem> itr = manager.iterator( );
while itr.hasNext( ) {
LibraryItem item = itr.next( );
// Do something with item.
}