java枚举enum实用小技巧!不看后悔!!

前言

早就知道枚举了,可却一直不知道合理去应用,今天发现一个小例子,才发现枚举真香!

enum应用

public enum  CountryEnum {
    ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FOUR(4,"赵"),FIVE(5,"魏"),SIX(6,"韩");


    private Integer retCode;
    private String retMessage;

    CountryEnum(Integer retCode, String retMessage) {
        this.retCode = retCode;
        this.retMessage = retMessage;
    }

    public Integer getRetCode() {
        return retCode;
    }

    public String getRetMessage() {
        return retMessage;
    }

    public static CountryEnum forEach_CountryEnum(int index){
    //代表每个枚举对象ONE TWO
        CountryEnum[] myArray = CountryEnum.values();
        for(CountryEnum ele:myArray){
            if(index == ele.getRetCode()){
                return ele;
            }
        }
        return null;
    }
}

test

public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for(int i = 1;i <=6;i++){
            new Thread(()->{

                System.out.println(Thread.currentThread().getName() + "\t 国灭亡");
                countDownLatch.countDown();
            },CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "====秦统一");
    }



-----------------
楚	 国灭亡
齐	 国灭亡
燕	 国灭亡
赵	 国灭亡
魏	 国灭亡
韩	 国灭亡
main====秦统一
全部评论

相关推荐

2025-12-18 18:23
深圳大学 前端工程师
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
Cl_Wg:看牛客匿名贴容易抑郁,白菜就是我的天花板
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务