Java Tutorial/Collections/Iterable Interface

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating Iterable Objects: using a for-each for loop on an Iterable object

import java.util.Iterator;
import java.util.NoSuchElementException;
// This class supports iteration of the 
// characters that comprise a string.
class IterableString implements Iterable<Character>, Iterator<Character> {
  private String str;
  private int count = 0;
  public IterableString(String s) {
    str = s;
  }
  // The next three methods implement Iterator.
  public boolean hasNext() {
    if (count < str.length()){
      return true;
    }  
    return false;
  }
  public Character next() {
    if (count == str.length())
      throw new NoSuchElementException();
    count++;
    return str.charAt(count - 1);
  }
  public void remove() {
    throw new UnsupportedOperationException();
  }
  // This method implements Iterable.
  public Iterator<Character> iterator() {
    return this;
  }
}
public class MainClass {
  public static void main(String args[]) {
    IterableString x = new IterableString("This is a test.");
    for (char ch : x){
      System.out.println(ch);
    }
  }
}



T
h
i
s
 
i
s
 
a
 
t
e
s
t
.


"for" statement for Iterable object in JDK 5 has been enhanced.

It can iterate over a Collection without the need to call the iterator method. The syntax is



for (Type identifier : expression) {
         statement (s)
     }



A
B
C
D


Iterable interface: while loop and for loop

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class MainClass {
  public static void main(String[] args) {
    List list = Arrays.asList("A", "B", "C", "D");
     Iterator iterator = list.iterator();
     while (iterator.hasNext () ) {
         String element = (String) iterator.next ();
         System.out.println(element);
     }
  }
}



A
B
C
D


Using an Iterator

The Iterator interface has the following methods:

  1. hasNext.
  2. next.
  3. remove.

Compared to an Enumeration, hasNext() is equivalent to hasMoreElements() and next() equates to nextElement().



import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class MainClass {
  public static void main(String[] a) {
    Collection c = new ArrayList();
    c.add("1");
    c.add("2");
    c.add("3");
    Iterator i = c.iterator();
    while (i.hasNext()) {
      System.out.println(i.next());
    }
  }
}



1
2
3