Java Reference
In-Depth Information
if the prior operation was previous ). Observe that next followed by previous
yields identical items.
Finally, we come to remove , which is extremely tricky because the seman-
tics of remove depend on which direction the traversal is proceeding. In fact,
this probably suggests a bad design in the Collections API: Method semantics
should not depend so strongly on which methods have been called prior to it.
But remove is what it is, so we have to implement it.
The implementation of remove begins with the test for structural modification
at line 156. If the prior iterator state change operation was a next , as evidenced by
the test at line 159 showing that nextCompleted is true , then we call the ArrayList
remove method (started at line 93 in Figure 15.14) that takes an index as a parame-
ter. The use of ArrayList.this.remove is required because the local version of
remove hides the outer class version. Because we have already advanced past the
item to be removed, we must remove the item in position current-1 . This slides
the next item from current to current-1 (since the old current-1 position has now
been removed), so we use the expression --current in line 160.
When traversing the other direction, we are sitting on the last item that
was returned, so we simply pass current as a parameter to the outer remove .
After it returns, the elements in higher indices are slid one index lower, so
current is sitting on the correct element and can be used in the expression at
line 162.
In either case, we cannot do another remove until we do a next or previous ,
so at line 166 we clear both flags. Finally, at line 167, we increase the value of
expectedModCount to match the container's. Observe that this is increased only
for this iterator, so any other iterators are now invalidated.
This class, which is perhaps the simplest of the Collections API classes
that contains iterators, illustrates why in Part Four we elect to begin with a
simple protocol and then provide more complete implementations at the end
of the chapter.
summary
This chapter introduced the inner class, which is a Java technique that is
commonly used to implement iterator classes. Each instance of an inner
class corresponds to exactly one instance of an outer class and automatically
maintains a reference to the outer class object that caused its construction. A
nested class relates two types to each other, while an inner class relates two
objects to each other. The inner class is used in this chapter to implement
the ArrayList .
The next chapter illustrates implementations of stacks and queues.
 
Search WWH ::




Custom Search