Creating Iterable Objects: using a for-each for loop on an Iterable object : Iterable Interface « Collections « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » Collections » Iterable Interface 
9.36.4.Creating Iterable Objects: using a for-each for loop on an Iterable objectPrevious/Next
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
.
9.36.Iterable Interface
9.36.1.Using an Iterator
9.36.2.Iterable interface: while loop and for loop
9.36.3.'for' statement for Iterable object in JDK 5 has been enhanced.
9.36.4.Creating Iterable Objects: using a for-each for loop on an Iterable object
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.