70 likes | 210 Views
Bag<T> implementation. Add(T item) Enlarge bag if necessary; allocate larger array Remove(T item) Reduce bag if necessary; allocate smaller array Iterator Visit each element of the Bag, in turn. Iterators. Iterator pattern. Horstmann book, pages 178-179 Carrano text, chapter 8
E N D
Bag<T> implementation • Add(T item) • Enlarge bag if necessary; allocate larger array • Remove(T item) • Reduce bag if necessary; allocate smaller array • Iterator • Visit each element of the Bag, in turn
Iterator pattern Horstmann book, pages 178-179 Carrano text, chapter 8 Various websites (here are just some): sourcemaking.com/design_patterns/iterator www.exciton.cs.rice.edu/JavaResources/DesignPatterns c2.com (down at the moment?)
Collection classes Each collection defines its own Iterator. Each collection needs to keep its implementation details private. Each iterator is defined as a separate class (so it can be instantiated independently of the class). Each iterator encapsulates iteration logic for a specific collection. It must know the implementation details in order to serve as the bridge between clients of the collection and the internal workings of that collection. How do we grant access to Iterator classes while denying access to others?
public interface Iterator<E> { /** * Returns <tt>true</tt> if the iteration has more elements. (In other * words, returns <tt>true</tt> if <tt>next</tt> would return an element * rather than throwing an exception.) * * @return <tt>true</tt> if the iterator has more elements. */ booleanhasNext(); /** * Returns the next element in the iteration. * * @return the next element in the iteration. * @exception NoSuchElementException iteration has no more elements. */ E next(); /** * * Removes from the underlying collection the last element returned by the * iterator (optional operation). This method can be called only once per * call to <tt>next</tt>. The behavior of an iterator is unspecified if * the underlying collection is modified while the iteration is in * progress in any way other than by calling this method. * * @exception UnsupportedOperationException if the <tt>remove</tt> * operation is not supported by this Iterator. * @exception IllegalStateException if the <tt>next</tt> method has not * yet been called, or the <tt>remove</tt> method has already * been called after the last call to the <tt>next</tt> * method. */ void remove(); } java.util.Iteratorjavadoc comments
Inner classes • Java’s Collection classes • concrete collection class must hide its implementation • must provide Iterator • Iterator must know implementation details • Inner class structure embeds Iterator definition within scope of collection class • Iterator can access internals of collection without collection having to break encapsulation