在今天培训上,讲师提到Enumeration接口,由于之前从来没有用过这个接口,查询API,发现此接口已经被Iterator所替代,但是为了知识点完成整性,所以还是学习一下这个接口。
java.util.Enumeration接口的功能和Iterator接口的功能是重复的。此外,Iterator 接口添加了一个可选的移除操作,并使用较短的方法名。新的实现应该优先考虑使用 Iterator 接口而不是 Enumeration 接口。
这个接口的主要作用是封装了有关枚举数据集合的遍历方法,Enumeration接口本身不是一个数据结构,但是,对其他数据接口非常重要;Enumeration接口定义了从一个数据结构得到连续数据的手段。
在这个接口中,只有两个方法,用于遍历这个集合,主要是
1.hasMoreElements()方法 : 测试此枚举是否包含更多的元素。
2.nextElement:如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。
Enumeration遍历的例子:
<span style="font-size:18px;">import java.util.*;
public class TestEnumeration {
public static void main(String[] args) {
Vector v = new Vector();
v.addElement("Li");
v.addElement("YYY");
v.addElement("Brown");
Enumeration e = v.elements();
while(e.hasMoreElements()){
String value = (String)e.nextElement();
System.out.println(value);
}
}
}</span>
演示Enumeration接口的使用:
<span style="font-size:18px;">import java.util.Enumeration;
public class MyEnumerationTest {
public static void main(String[] args) {
MyDataCollection collection = new MyDataCollection();
Enumeration enumeration = collection.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
class MyDataCollection {
String[] datas = null;
public MyDataCollection() {
datas = new String[4];
datas[0] = "zero";
datas[1] = "one";
datas[2] = "two";
datas[3] = "three";
}
public MyEnumeration elements() {
return new MyEnumeration(0, 4, datas);
}
}
/**
* 自定义Enumeration
*/
class MyEnumeration implements Enumeration {
int count; // 计数器
int length; // 存储的数组的长度
Object[] dataArray; // 存储数据数组的引用
// 构造器
MyEnumeration(int count, int length, Object[] dataArray) {
this.count = count;
this.length = length;
this.dataArray = dataArray;
}
public boolean hasMoreElements() {
return (count < length);
}
public Object nextElement() {
return dataArray[count++];
}
}</span>