Enumeration介绍
百度翻译为【枚举】,接口类型并支持泛型。
作用:遍历集合
声明方法 | 描述 |
---|---|
boolean hasMoreElements() | 判读是否还存在元素 |
E nextElement() | 返回下一个元素的值,如果没有抛出异常 |
源码作者:
- @author Lee Boynton
- @since JDK1.0
示例
示例描述:遍历交通灯的三个颜色
- 定义颜色类实现Enumeration
- 定义常量颜色字符串数组
- 遍历查看结果
自定义类
package practice.collection.zzj;
import java.util.Enumeration;
import java.util.NoSuchElementException;
/**
* 颜色待遍历类
*/
public class ColorEnumeration implements Enumeration<String> {
// 等待遍历数组(集合)
private final String[] colors = new String[]{"Red","Green","Yellow"};
// 当前数组索引
int currenIndex = 0;
// 数组最大索引
final int maxIndex = colors.length;
/**
* 判断是否有元素
* @return
*/
@Override
public boolean hasMoreElements() {
if(currenIndex<maxIndex){
return true;
}
return false;
}
/**
* 获取当前元素
* @return
*/
@Override
public String nextElement() {
if(currenIndex<maxIndex){
return colors[currenIndex++];
}else{
throw new NoSuchElementException("color array empty");
}
}
}
启动类
import practice.collection.zzj.ColorEnumeration;
public class Main {
public static void main(String[] args){
ColorEnumeration colorEnumeration = new ColorEnumeration();
// 遍历颜色
while(colorEnumeration.hasMoreElements()){
System.out.println(colorEnumeration.nextElement());
}
}
}
结果
Red
Green
Yellow
Process finished with exit code 0
已知实现常见类
java.util.Hashtable
java.util.Vector
这两个类中都有一个 elements()方法获取Enumeration实现类