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的name 40 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 }