Utiliser la boucle ‘foreach’ pour parcourir un objet Iterable

Author:


{filelink=4411}

import java.util.*;

class StrIterable implements Iterable,
                             Iterator {
  private String str;
  private int count = 0;

  StrIterable(String s) {
    str = s;
  }

  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();
  }

  public Iterator iterator() {
    return this;
  }
}

public class MainClass {
  public static void main(String args[]) {
    StrIterable x = new StrIterable("C'est un test.");

    for(char ch : x)
      System.out.print(ch);

    System.out.println();
  }
}

A Voir sur le même Sujet:

  • jstl tag for-each imbriqué
  • C# iterable object
  • parcourir objet java
  • parcourir une collection avec foreach java
  • boucle foreach pour parcourir une collection
  • afficher un char javascript
  • afficher un char en java
  • afficher contenu char[] en java
  • code+source++pour+parcourir+un+objet

Leave a Reply

Your email address will not be published. Required fields are marked *