Monday, August 12, 2013

Implement Iterator for Array

Official Java Documents for Iterable Interface: java.lang.Iterable.
Official Java Documents for Iterator Interface: java.util.Iterator.

 public class MyIterable<E> implements Iterable<E> {  
   E[] elems;  
   int nElems;  

   /**
    * Constructor.
    */
   public MyIterable(E[] data) {  
     this.elems = data;  
     nElems = data.length;  
   }  

   /**
    * Returns an iterator over a set of elements of type E.
    */
   public Iterator<E> iterator() {  
     return new MyIterator<E>();  
   }  
   
   private class MyIterator<E> implements Iterator<E> {  
     int nextElem = 0;  
     boolean hasRemoved = true;  
   
     /**  
      * Returns true if the iteration has more elements.  
      * In other words, returns true if next() would return an element  
      * rather than throwing an exception.  
      */  
     public boolean hasNext() {  
       return nextElem < nElems;  
     }  
   
     /**  
      * Returns the next element in the iteration.  
      *   
      * Throws: java.util.NoSuchElementException if the iteration has no more elements  
      */  
     public E next() {  
       if (!hasNext()) {  
         throw new NoSuchElementException("No more elements");  
       }  
   
       E e = elems[nextElem];  
       ++nextElem;  
       hasRemoved = false;  
       return e;  
     }  
   
     /**  
      * Removes from the underlying collection the last element returned by this iterator.  
      * This method can be called only once per call to next(). 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.  
      *   
      * Throws: java.lang.IllegalStateException if the next method has not yet been called,  
      * or the remove method has already been called after the last call to the next method.  
      */  
     public void remove() {  
       if (hasRemoved) {  
         throw new IllegalStateException(  
           "The remove method can only be called once and after the next method.");  
       }  
   
       if (nextElem < nElems - 1) {  
         System.arraycopy(elems, nextElem+1, elems, nextElem, nElems-nextElem-1);  
       }  
       --nElems;  
       hasRemoved = true;  
     }  
   }  
 }  

No comments:

Post a Comment