首页 > 编程语言 > 详细

Java 枚举使用三板斧

时间:2019-07-23 14:13:26      阅读:98      评论:0      收藏:0      [点我收藏+]

Java 枚举使用三板斧

1 定义

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

  private Integer retCode;
  private String retMsg;

  // 枚举的构造方法是 private 的
  private CountryEnums(Integer retCode,String retMsg){
    this.retCode = retCode;
    this.retMsg = retMsg;
  }

  public Integer getRetCode() {
    return retCode;
  }

  public void setRetCode(Integer retCode) {
    this.retCode = retCode;
  }

  public String getRetMsg() {
    return retMsg;
  }

  public void setRetMsg(String retMsg) {
    this.retMsg = retMsg;
  }
2 遍历
  // 枚举的遍历
  public static CountryEnums forEachCountryEnums(Integer index){
    for(CountryEnums element : values()){
      if(element.getRetCode() == index){
        return element;
      }
    }
    return null;
  }
}

 

3 使用

for(int i = 1; i <= 6; i++){

  System.out.println(CountryEnums.forEachCountryEnums(i).getRetMsg());
}

 

 

Java 枚举使用三板斧

原文:https://www.cnblogs.com/karong007/p/11230029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!