Java Reference
In-Depth Information
Its implementation requires two methods: hasMoreElements and nextElement .
Note that nextElement yields an Object ; this method has been made as gener-
al as possible.
A class that enumerates Strings
We use interface Enumeration to write a class (see Fig. 12.7) that provides
an enumeration of the characters of a string. Class StringEnumeration needs
two fields: the string whose characters are to be enumerated and an integer that
indicates the next character to be listed. Integer k is initially 0 because s[0] is
the first character in the enumeration. Note that we describe in comments what
fields k and s are for. Always describe fields of using such a class invariant.
The constructor for StringEnumeration has one parameter, a string. This
parameter is stored in field s .
Method hasMoreElements is easy to write. Since k is the next element to
list, there are more elements if and only if k is less than the length of the String .
The specification of method nextElement requires us to check whether
there is indeed another element and to throw an exception (see Chap. 10) if there
is not. If there is another element, k can be incremented and the character can be
returned. Note that a value of type char cannot be returned because nextEle-
ment has to return an Object . Therefore, the char to be returned is wrapped in
an object of wrapper class Character .
Activity 12-4.2
shows how
easy it is to
change this
into a class to
/** An enumeration of the characters in a String , as instances of class Character . */
public class StringEnumeration implements Enumeration {
private String s; // The string to be enumerated
private int k= 0; // s[k] is next char. to be enumerated (none if k = s.length())
/** Constructor: an instance to enumerate characters of sp */
public StringEnumeration(String sp)
{ s= sp; }
/** = " there are more elements to enumerate " */
public boolean hasMoreElements()
{ return k < s.length(); }
/** = The next element to enumerate --it is of class Character */
public Object nextElement() {
if (!hasMoreElements())
{ throw new NoSuchElementException("no more characters"); }
k= k + 1;
return new Character(s.charAt(k - 1));
Figure 12.7:
Class StringEnumeration
Search WWH ::

Custom Search