Java enumeration (enum) common operation notes

foreword

  • A Java enumeration is a special class that generally represents a set of constants, such as 4 seasons in a year, 12 months in a year, 7 days in a week, and directions such as east, west, north, and so on.

  • An enumeration is a collection of named integer constants used to declare a set of constants with identifiers.

  • The Java enumeration class is defined using enumthe keyword , and each constant ,is separated by a comma.

  • The internal construction method of the enumeration is private , and there is no problem if the construction method does not write private.

In the following case, we define an enumeration class around the seasons SeasonEnum, and introduce its usage according to the enumeration class.

1. Use of enumeration class constants

1.1 Define an enumeration class

When defining an enumeration class, it is recommended to add a suffix at the end Enum, for example SeasonEnum, the instance object of the enumeration type is recommended to be all capitalized

public enum SeasonEnum {
    
    
	// 每个枚举常量之间用,进行分割,系统会为这些常量自动添加 public static final修饰
	SPRING, SUMMER, AUTUMN, WINTER
}

1.2 Common methods

  1. Directly use the SeasonEnum enumeration class to call the enumeration constant
  2. Directly call values()the method of the enumeration class to obtain the array of enumeration constants , and call for a certain enumeration constant to ordinal()obtain its subscript
  3. Call valueOf(String s)the method of the enumeration class, pass in the String variable to obtain the enumeration constant
  4. Logical judgment with switch statement
public static void main(String[] args) {
    
    

    // 1、直接调用枚举类型                    // 如下为打印结果
    System.out.println(SeasonEnum.SPRING); // SPRING
    System.out.println(SeasonEnum.SUMMER); // SUMMER
    System.out.println(SeasonEnum.AUTUMN); // AUTUMN
    System.out.println(SeasonEnum.WINTER); // WINTER

	// 2、直接调用枚举类的values()方法,得到枚举常量数组
	SeasonEnum[] seasonEnums = SeasonEnum.values();
	//   针对某一个枚举常量调用ordinal()方法获取其下标,下标从0开始
    for (SeasonEnum seasonEnum : seasonEnums) {
    
    
        System.out.println(seasonEnum + "下标为:" + seasonEnum.ordinal());
        // SPRING下标为:0
		// SUMMER下标为:1
		// AUTUMN下标为:2
		// WINTER下标为:3      
    }
 
    // 3、通过枚举类型获取SUMMER的枚举类型
    String summer = "SUMMER";
    SeasonEnum seasonEnum = SeasonEnum.valueOf(summer);
    System.out.println(seasonEnum);        // SUMMER
    
    // 4、搭配switch语句使用
    switch (seasonEnum) {
    
    
        case SPRING:
            System.out.println("春天");
            break;
        case SUMMER:
            System.out.println("夏天");     // 夏天
            break;
        case AUTUMN:
            System.out.println("秋天");
            break;
        case WINTER:
            System.out.println("冬天");
            break;
    }
}

2. Advanced use of enumeration class constants

2.1 Define an enumeration class

  1. Define an enumeration with parameters, that is, add member variables
  2. Add new static method to enum
  3. Overriding enumeration methods
public enum SeasonEnum {
    
    

    SPRING("春天",3), SUMMER("夏天",6), AUTUMN("秋天",9), WINTER("冬天",12);

	// 1、定义季节中文名字和季节月份成员变量
    private String name;
    private int month;

    // 枚举类型的构造方法默认时私有的,系统会自动添加 private 修饰
    SeasonEnum (String name, int month) {
    
    
        this.name = name;
        this.month = month;
    }

	// 2、向枚举中添加新方法, 根据月份返回季节中文名字
    public static String getName(int month){
    
    
        for (SeasonEnum seasonType : SeasonEnum.values()) {
    
    
            if (seasonType.getMonth() == month) {
    
    
                return seasonType.getName();
            }
        }
        return null;
    }

	// 3、覆盖枚举的toString()方法
	@Override
    public String toString() {
    
    
        return "SeasonEnum{" +
                "name='" + name + '\'' +
                ", month=" + month +
                '}';
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getMonth() {
    
    
        return month;
    }

    public void setMonth(int month) {
    
    
        this.month = month;
    }
}

2.2 Example of method call

  1. After overriding toString()the method, print the basic information of the enumeration constant
  2. Call the custom static method to get the Chinese name of the season according to the month
  3. Obtain the member variable information corresponding to the enumeration constant
  4. Modify the member variable information corresponding to the enumeration constant
public static void main(String[] args) {
    
    

    // 1、打印枚举常量基础信息
    SeasonEnum[] seasonEnums = SeasonEnum.values();
    for (SeasonEnum seasonEnum : seasonEnums) {
    
    
        System.out.println(seasonEnum);
        // SeasonEnum{name='春天', month=3}
        // SeasonEnum{name='夏天', month=6}
        // SeasonEnum{name='秋天', month=9}
        // SeasonEnum{name='冬天', month=12}
    }

    // 2、调用自定义的静态方法,根据月份获取季节中文名字
    String season = SeasonEnum.searchName(12);
    System.out.println(season);  // 冬天

    // 3、获取枚举常量对应的成员变量信息
    SeasonEnum spring = SeasonEnum.SPRING;
    String name = spring.getName();
    int month = spring.getMonth();
    System.out.println("当前季节是:" + name + ", 所处月份为:" + month); // 当前季节是:春天, 所处月份为:3

    // 4、修改枚举常量对应的成员变量信息
    spring.setName("春天到了");
    spring.setMonth(1);
    System.out.println(spring);  // SeasonEnum{name='春天到了', month=1}
}

Guess you like

Origin blog.csdn.net/weixin_43730812/article/details/128468051