Java Reference
In-Depth Information
Question 15 If the iterator's position is between the first two entries of the previous list, write
Java statements that replace Josh with Jon.
15.39
Example: The method add . The method add inserts an entry into the list just before the iterator's
current position. Thus, the insertion is made immediately before the entry, if any, that next would
have returned before add was called and just after the entry, if any, that previous would have
returned. Note that if the list is empty, add inserts a new entry as the only entry in the list.
If the iterator's position is currently between the first two entries of the previous list , the statement
traverse.add("Ashley");
adds Ashley to the list just before Jim —that is, at index 1 or, equivalently, at list position 2. After
this addition, the list is as follows:
Jen
Ashley
Jim
Josh
A call to next at this point returns Jim, since next would have returned Jim had we not called
add . If, however, we call previous instead of next , the new entry Ashley will be returned. Further-
more, the addition increases by 1 the values that nextIndex and previousIndex will return. Thus,
immediately after the addition, nextIndex will return 2 and previousIndex will return 1.
Question 16 If the iterator's position is between Ashley and Jim, write Java statements that
add Miguel right after Jim.
15.40
Example: The method remove . The behavior of the method remove is similar to that of remove in
the interface Iterator , which you saw earlier in this chapter. But in the interface ListIterator ,
remove is affected by the method previous as well as by next . Thus, remove removes the list entry
that the last call to either next or previous returned.
If the list contains
Jen
Ashley
Jim
Josh
and the iterator traverse is positioned between Ashley and Jim, the statements
traverse.previous();
traverse.remove();
remove Ashley from the list, since previous returns Ashley. The iterator's position remains just
before Jim.
Notice that both set and remove will throw the exception IllegalStateException if neither next
nor previous has been called, or if either remove or add has been called already since the last call to next
or previous . As you will see in the next section, this behavior complicates the implementation somewhat.
An Array-Based Implementation of the Interface ListIterator
15.41
As we did for the interface Iterator earlier in this chapter, we will implement the interface List-
Iterator as an inner class of a class that uses an array to represent the ADT list. First, we define an
 
 
Search WWH ::




Custom Search