Java Reference
In-Depth Information
Question 8
Given the class
LinkedListWithIterator
, what Java statements create the
iterators
nameIterator
and
countingIterator
mentioned in Segment 15.11?
Question 9
Revise the method
displayList
, as shown in Listing 12-2 of Chapter 12, for use
in a client of the class
LinkedListWithIterator
by using iterator methods to display the list.
For the array-based implementation, our iterator will support the
remove
method. Let's begin with
the array-based implementation of the ADT list,
AList
, as given in Chapter 13. Our new class,
whose form is shown in Listing 15-5, has the same data fields and methods as the class
AList
. But
since our new class implements the interface
ListWithIteratorInterface
, it also includes the
method
getIterator
. Our class also contains the inner class
IteratorForArrayList
, which imple-
ments the interface
Iterator
.
LISTING 15-5
An outline of the class
ArrayListWithIterator
import
java.util.Iterator;
import
java.util.NoSuchElementException;
public
class
ArrayListWithIterator<T>
implements
ListWithIteratorInterface<T>
{
private
T[] list;
// array of list entries
private
int
numberOfEntries;
private
static
final
int
DEFAULT_INITIAL_CAPACITY = 25;
public
ArrayListWithIterator()
{
this
(DEFAULT_INITIAL_CAPACITY);
}
// end default constructor
public
ArrayListWithIterator(
int
initialCapacity)
{
numberOfEntries = 0;
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempList = (T[])
new
Object[initialCapacity];
list = tempList;
}
// end constructor
< Implementations of the methods of the ADT list go here;
you can see them in Chapter 13, beginning at Segment 13.5.>
. . .
public
Iterator<T> getIterator()
{
return
new
IteratorForArrayList();
}
// end getIterator