java笔记--零碎--Enumeration

Enumeration介绍

百度翻译为【枚举】,接口类型并支持泛型。
作用:遍历集合

声明方法描述
boolean hasMoreElements()判读是否还存在元素
E nextElement()返回下一个元素的值,如果没有抛出异常

源码作者:

  • @author Lee Boynton
  • @since JDK1.0

示例

示例描述:遍历交通灯的三个颜色

  1. 定义颜色类实现Enumeration
  2. 定义常量颜色字符串数组
  3. 遍历查看结果

自定义类

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实现类

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值