Using a foreach(for each) for loop on an Iterable object. : Foreach « Language Basics « Java






Using a foreach(for each) for loop on an Iterable object.

import java.util.*; 
 
class StrIterable implements Iterable<Character>, 
                             Iterator<Character> { 
  private String str; 
  private int count = 0; 
 
  StrIterable(String s) { 
    str = s; 
  } 
 
  // The next three methods impement 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[]) {  
    StrIterable x = new StrIterable("This is a test."); 
 
    for(char ch : x) 
      System.out.print(ch); 
 
    System.out.println(); 
  }  
}
           
       








Related examples in the same category

1.Foreach ArrayForeach Array
2.Simple demo to print all the types of an enumSimple demo to print all the types of an enum
3.Foreach and generic data structureForeach and generic data structure
4.Use a foreach(for each) style for loop.Use a foreach(for each) style for loop.
5.Use break with a foreach(for each) style for.Use break with a foreach(for each) style for.
6.The foreach(for each) loop is essentially read-only.
7.Use foreach(for each) style for on a two-dimensional array.
8.Search an array using foreach(for each) style for.
9.Using a foreach(for each) for loop with a collection.
10.Java for In(forin) TesterJava for In(forin)  Tester
11.Java for in (forin) with CollectionJava for in (forin) with Collection
12.Java for in (forin) with generic CollectionJava for in (forin) with generic Collection
13.Java for in (forin): line-by-line iteration through a text fileJava for in (forin): line-by-line iteration through a text file