Java Reference
In-Depth Information
you really do want to remove it. The exceptions that the remove() method can throw are also derived from
RuntimeException so you are not obliged to catch them.
Of course, you can also iterate over the strings in the list like this:
for(String string : strings) {
// Do something with string...
}
Implementing an Iterator Capability
As I said in the previous section, the iterator() method in the LinkedList<T> type must return an object
reference as type Iterator<T> , so the class type for the iterator object should implement the Iterator<T>
interface. An iterator is a one-time use object so you need to recreate it each time. You could define a class
representing an iterator as an inner class to LinkedList<T> :
import java.util.Iterator;
public class LinkedList<T> implements Iterable<T> {
// Returns an iterator for this list
public Iterator<T> iterator() {
return new ListIterator();
// Create iterator of the inner class type
}
// Inner class defining iterator objects for this linked list
private class ListIterator implements Iterator<T> {
// Constructor
public ListIterator() {
// Code to initialize the iterator...
}
// Method to test whether more elements are available
public boolean hasNext() {
// Code to determine if there are more elements...
}
// Method to return the next available object from the linked list
public T next() {
// Code to return the next element...
}
// Method to remove the last element retrieved from the linked list
public void remove() {
// Code to remove the element last accessed by next()...
}
// Any other members needed for ListIterator<T>...
}
// Rest of the LinkedList<T> generic type definition as before ...
}
Search WWH ::




Custom Search