APCS Java Subset

ap.java.util
Interface Iterator

All Known Subinterfaces:
ListIterator

public interface Iterator

This interface provides an abstraction for obtaining elements one at a time from some source, typically a collection like a Set, List, or Map. However, it is also possible to construct class implementing the Iterator interface for obtaining words one at a time from a file or a URL, for example. The Iterator interface is only used in the AB course.

Code for printing all the values in a Set uses an iterator as follows:


    public static void printSet(Set s)
    {
        Iterator it = s.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
     } 
 

The code below uses the remove method to delete all occurrences of "hello" from a List of String elements:

     public static void removeHello(List list)
     {
         Iterator it = list.iterator();
         while (it.hasNext()) {
             String str = (String) it.next();
             if (str.equals("hello")) {
                 it.remove();
             }
         }
     }
 


Method Summary
 boolean hasNext()
          Returns true if the iteration has more elements.
 java.lang.Object next()
          Returns the next element in this iteration.
 void remove()
          Removes the last element returned by this iterator (by calling next) from the collection being iterated over.
 

Method Detail

hasNext

public boolean hasNext()
Returns true if the iteration has more elements. When true is returned, the next method returns an element from the iteration, otherwise next throws an exception.

Returns:
true if there are more elements in this iteration, otherwise returns false

next

public java.lang.Object next()
Returns the next element in this iteration.

Returns:
the next element in this iteration
Throws:
NoSuchElementException - if there are no more elements in this iteration

remove

public void remove()
Removes the last element returned by this iterator (by calling next) from the collection being iterated over. This method should only be called once per call of next. This method is an optional operation, it is legal for an iterator to throw a java.lang.UnsupportedOperationException exception when remove is called.

Throws:
java.lang.UnsupportedOperationException - if this method is not implemented
IllegalStateException - if next has not been called or if remove has been called after the last call of next

unofficial documentation for the APCS Java Subset