TestEnumeration1.java
Select all
/* TestEnumeration1.java CIS 260 2/16/2005 David Klick Demonstrates how you can create an Enumeration class for your own classes. */ import java.util.*; public class TestEnumeration1 { public static void main(String[] args) { MyString s = new MyString("There once was a mighty sailing man"); Enumeration e = s.characters(); while (e.hasMoreElements()) System.out.print(e.nextElement()); } } class MyString { private String str; // creating new Strings is overkill, but I want // to get you used to not sharing references // to private variables MyString(String s) { str = new String(s); } String getString() { return new String(str); } public Enumeration characters() { return new Enum(); } private class Enum implements Enumeration { private int pos = 0; public boolean hasMoreElements() { return str.length() > pos; } public Object nextElement() throws NoSuchElementException { if (!hasMoreElements()) throw new NoSuchElementException(); else return new Character(str.charAt(pos++)); } } }