Question: To implement the preorder method of the AbstractTree class, we relied on the convenience of creating a snapshot. Reimplement a preorder method that creates a
To implement the preorder method of the AbstractTree class, we relied on the convenience of creating a snapshot. Reimplement a preorder method that creates a lazy iterator. (See Section 7.4.2 for discussion of iterators.)
Section 7.4.2
?
/- /** * A (nonstatic) inner class. Note well that each instance contains an implicit * reference to the containing list, allowing it to access the list's members. nested Arraylterator class 3. 4 private class Arraylterator implements Iterator { private int j = 0; private boolean removable = false; // can remove be called at this time? 6 // index of the next element to report 7 8. /** Tests whether the iterator has a next object. * @return true if there are further objects, false otherwise */ public boolean hasNext() { return j < size; } // size is field of outer instance 10 11 12 13 14 15 /** * Returns the next object in the iterator. 16 17 18 * @return next object * @throws NoSuchElementException if there are no further elements */ public E next() throws NoSuchElementException { if (j == size) throw new NoSuchElementException("No next element"); removable = true; // this element can subsequently be removed return datalj++]; / post-increment j, so it is ready for future call to next } 19 20 21 22 23 24 25 26 27 /** * Removes the element returned by most recent call to next. * @throws IllegalStateException if next has not yet been called * Othrows IllegalStateException if remove was already called since recent next 28 29 30 31 32 public void remove(() throws IllegalStateException { if (Iremovable) throw new IllegalStateException("nothing to remove"); Array List.this.remove(j-1); // that was the last one returned j--; removable = false; } } /- 33 34 35 // next element has shifted one cell to the left // do not allow remove again until next is called 36 37 38 39 - end of nested Arraylterator class 40 /** Returns an iterator of the elements stored in the list. */ public Iterator iterator() { return new Arraylterator(); } 41 42 43 // create a new instance of the inner class 44
Step by Step Solution
3.34 Rating (163 Votes )
There are 3 Steps involved in it
To implement the preorder method of the AbstractTree class using a lazy iterator we can create a private inner class called PreorderIterator that impl... View full answer
Get step-by-step solutions from verified subject matter experts
