interface Iterable

from<thinking in java>

 

The reason that this works is that Java SE5 introduced a new interface called Iterable which
contains an iterator( ) method to produce an Iterator, and the Iterable interface is what
foreach uses to move through a sequence. So if you create any class that implements
Iterable, you can use it in a foreach statement: 

public class IterableClass implements Iterable<String> { 
  protected String[] words = ("And that is how " + 
    "we know the Earth to be banana-shaped.").split(" "); 
  public Iterator<String> iterator() { 
    return new Iterator<String>() { 
      private int index = 0; 
      public boolean hasNext() { 
        return index < words.length; 
      } 
      public String next() { return words[index++]; } 
      public void remove() { // Not implemented 
        throw new UnsupportedOperationException(); 
      } 
    }; 
  }  
  public static void main(String[] args) { 
    for(String s : new IterableClass()) 
      System.out.print(s + " "); 
  } 
} /* Output: 
And that is how we know the Earth to be banana-shaped. 
*///:~ 
public class IterableClass implements Iterable<String> { 
  protected String[] words = ("And that is how " + 
    "we know the Earth to be banana-shaped.").split(" "); 
  public Iterator<String> iterator() { 
    return new Iterator<String>() { 
      private int index = 0; 
      public boolean hasNext() { 
        return index < words.length; 
      } 
      public String next() { return words[index++]; } 
      public void remove() { // Not implemented 
        throw new UnsupportedOperationException(); 
      } 
    }; 
  }  
  public static void main(String[] args) { 
    for(String s : new IterableClass()) 
      System.out.print(s + " "); 
  } 
} /* Output: 
And that is how we know the Earth to be banana-shaped. 
*///:~ 

 

你可能感兴趣的:(interface)