Sample custom iterator functionality implemented by Java

  • 2020-06-19 10:21:18
  • OfStack

This article gives an example of the custom iterator functionality implemented by Java. To share for your reference, specific as follows:

Write your own Iterator, Iterator interface, Iterable implementation, you can use the "foreach" loop through your object.


import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 *  demo Iterator and Iterable Interface, and how to write it 1 A simple iterator for an object array. 
 */
public class AarrayIterator<T> implements Iterable<T>, Iterator<T> {
  private final static String[] names = {"rose", "petunia", "tulip"};
  public static void main(String[] args) {
    AarrayIterator<String> arrayIterator = new AarrayIterator<>(names);
    // Java 5,6 The way of 
    for (String s : arrayIterator) {
      System.out.println(s);
    }
    // Java 8 In the form of 
    arrayIterator.forEach(System.out::println);
  }
  /**
   *  The data to traverse 
   **/
  protected T[] data;
  protected int index = 0;
  /**
   *  structure 1 a AarryIterator Object. 
   *
   * @param data  An array of objects to be iterated over 
   */
  public AarrayIterator(final T[] data) {
    setData(data);
  }
  /**
   *  Sets (resets) the array to the given array, resets the iterator. 
   *  parameter d Represents the array object being iterated over. 
   *
   * @param d  The array object being iterated over 
   */
  public void setData(final T[] d) {
    this.data = d;
    index = 0;
  }
  /**
   *  If not the end, return true , for instance, if next() The statement will execute successfully. 
   *  Otherwise returns false, perform if next() Statement throws an exception. 
   *
   * @return
   */
  public boolean hasNext() {
    return index < data.length;
  }
  /**
   *  Returns the following of the data 1 An element 
   *
   * @return
   */
  public T next() {
    if (hasNext()) {
      return data[index++];
    }
    throw new NoSuchElementException("only " + data.length + " elements");
  }
  public void remove() {
    throw new UnsupportedOperationException("This demo Iterator does not implement the remove method");
  }
  /**
   * Iterator The method of 
   *
   * @return
   */
  public Iterator<T> iterator() {
    index = 0;
    return this;
  }
}

Execution Results:


rose
petunia
tulip
rose
petunia
tulip

I hope this article has been helpful in java programming.


Related articles: