Creating Custom Enumerations : Enumeration Interface « Collections « Java Tutorial






import java.lang.reflect.Array;
import java.util.Enumeration;

class ArrayEnumeration implements Enumeration {
  private final int size;

  private int cursor;

  private final Object array;

  public ArrayEnumeration(Object obj) {
    Class type = obj.getClass();
    if (!type.isArray()) {
      throw new IllegalArgumentException("Invalid type: " + type);
    }
    size = Array.getLength(obj);
    array = obj;
  }

  public boolean hasMoreElements() {
    return (cursor < size);
  }

  public Object nextElement() {
    return Array.get(array, cursor++);
  }
}

public class MainClass {

  public static void main(String args[]) {
    Object obj = new int[] { 2, 3, 5, 8, 13, 21 };
    Enumeration e = new ArrayEnumeration(obj);
    while (e.hasMoreElements()) {
      System.out.println(e.nextElement());
    }
    try {
      e = new ArrayEnumeration("Not an Array");
    } catch (IllegalArgumentException ex) {
      System.out.println(ex.getMessage());
    }
  }
}
2
3
5
8
13
21
Invalid type: class java.lang.String








9.35.Enumeration Interface
9.35.1.The Enumeration Interface
9.35.2.If you prefer a for-loop
9.35.3.Where do we get the enumeration from?
9.35.4.The SequenceInputStream Class
9.35.5.Concatenates the content of two enumerations into one.
9.35.6.Filters enumeration to contain each of the provided elements just once.
9.35.7.Filters some elements out from the input enumeration.
9.35.8.For each element of the input enumeration asks the Processor to provide a replacement
9.35.9.Removes all nulls from the input enumeration.
9.35.10.Returns an enumeration that iterates over provided array.
9.35.11.Support for breadth-first enumerating.
9.35.12.Serializable Enumeration
9.35.13.An enumeration that iterates over an array.
9.35.14.Creating Custom Enumerations