你的位置:首页 > Java教程

[Java教程]Java enum


 

 1 /** 2  * Created by Edward on 2016/6/30. 3 */ 4 public class TestEnum { 5  6   //方法一 7   public enum SexEnum{ 8     MALE,FEMALE; 9   }10 11   //方法二12   public enum SexEnum1{13     MALE(1),14     FEMALE(2);15 16     private int id;17 18     //私有构造函数19     private SexEnum1(int id)20     {21       this.id=id;22     }23 24     //获取值对应的enum对象25     public static SexEnum1 getEnum(int id)26     {27       for(SexEnum1 s : SexEnum1.values())28       {29         if(s.id == id)30         return s;31       }32       return null;33     }34   }35 36 37   public static void main(String[] argv)38   {39     //列出enum的name40     for(SexEnum sex : SexEnum.values())41       System.out.println(sex.name());42 43     //通过 ENUM 访问44     SexEnum sex = SexEnum.MALE;45     switch(sex)46     {47       case MALE:48         System.out.println("男性");49         break;50       case FEMALE:51         System.out.println("女性");52         break;53       default:54         System.out.println("其他");55         break;56     }57 58     //通过值获取 enum对象59     SexEnum1 s = SexEnum1.getEnum(3);60     switch(s)61     {62       case MALE:63         System.out.println("男");64         break;65       case FEMALE:66         System.out.println("女");67         break;68       default:69         System.out.println("其他");70         break;71     }72 73   }74 }