1.枚举简介
枚举是由一组固定的常量组成的类型,自定义数据类型,
枚举的常量值一定是可列举的有限值。常量值的类型都是public static final
[修饰符] enum enumName{ 常量值1, 常量值2, 常量值3… 常量值n[;] }
Gender 是一种自定义的数据类型,可以用于声明变量,且变量的取值必须是枚举值的其中一个。gender的值必须是男或者女或者保密。
public static void main(String[] args) { // 声明一个Gender枚举类型的变量gender,并取值为男 Gender gender = Gender.男; }
java中所有的枚举类型都继承于Enum类。可以把枚举类型看出一个类。
public class Student { private String name; private int age; private Gender gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public Student(String name, int age, Gender gender) { super(); this.name = name; this.age = age; this.gender = gender; } public Student() { super(); } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } } // class Gender extends Enum{} enum Gender { 男, 女, 保密; }
1.2 枚举和字符串转化
public static void main(String[] args) { // 声明一个Gender枚举类型的变量gender,并取值为男 Gender gender = Gender.男; // 枚举值->字符串 System.out.println(gender.toString()); // 字符串串-> 枚举值 String str = "保密"; // 可能产生IllegalArgumentException 非法参数异常 Gender gender2 = Enum.valueOf(Gender.class, str); System.out.println(gender2); }
1.3 枚举和switch
public enum Week { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; }
public static void main(String[] args) { // 需求:有一个变量表示星期几,输出对于的教学安排 Week week = Week.TUESDAY; switch (week) { case MONDAY: case TUESDAY: case THURSDAY: case FRIDAY: case SATURDAY:{ System.out.println("上课"); break; } case WEDNESDAY: case SUNDAY:{ System.out.println("练习"); break; } } }
枚举的其他方法
public static void main(String[] args) { // 枚举变量的其他方法 Week week = Week.SUNDAY; System.out.println(week.name()); System.out.println(week.ordinal()); }