Java's enumeration type (`enum type`) usage method detailed explanation

1 background

javaBefore enumeration types were introduced into the language, the common pattern for representing enumeration types was to declare a group with constants int. Previously, we usually use public final staticthe method to define the code as follows, using 1 to represent spring, 2 to represent summer, 3 to represent autumn, and 4 to represent winter.

public class Season {
    public static final int SPRING = 1;
    public static final int SUMMER = 2;
    public static final int AUTUMN = 3;
    public static final int WINTER = 4;
}

This approach is called int enumeration mode. But what's the problem with this model? We've been using it for so long, so it should be fine. Usually the code we write will consider its security , ease of use and readability . First, let's consider its type safety . Of course this pattern is not type safe . For example, we design a function that requires a certain value of spring, summer, autumn and winter to be passed in. But using the int type, we cannot guarantee that the value passed in is legal. The code looks like this:

private String getChineseSeason(int season){
        StringBuffer result = new StringBuffer();
        switch(season){
            case Season.SPRING :
                result.append("春天");
                break;
            case Season.SUMMER :
                result.append("夏天");
                break;
            case Season.AUTUMN :
                result.append("秋天");
                break;
            case Season.WINTER :
                result.append("冬天");
                break;
            default :
                result.append("地球没有的季节");
                break;
        }
        return result.toString();
    }

    public void doSomething(){
        System.out.println(this.getChineseSeason(Season.SPRING));//这是正常的场景

        System.out.println(this.getChineseSeason(5));//这个却是不正常的场景,这就导致了类型不安全问题
    }

Programs getChineseSeason(Season.SPRING)are our intended usage methods. But getChineseSeason(5)obviously not, and the compilation will pass, we don't know what will happen at runtime. This obviously does not conform to Javathe type safety of the program.

Next, let's consider the readability of this pattern . Most of the time I use enums, I need to be able to easily get a string expression of the enum type. If we intprint out the enum constants, all we see is a set of numbers, which isn't very useful. We might think of using Stringconstants instead of intconstants. While it provides printable strings for these constants, it can cause performance issues because it relies on string comparison operations, so this mode is also undesirable. Considering both type safety and program readabilityint , the shortcomings of Stringthe enumeration mode are revealed. Fortunately, since Java1.5the release, an alternative solution has been proposed that avoids intthe Stringdisadvantages of the enum pattern and provides many additional benefits. That is the enumeration type ( enum type). The following chapters will introduce the definition, characteristics, application scenarios, advantages and disadvantages of enumerated types.

2 definitions

An enumerated type ( enum type) refers to a legal type composed of a fixed set of constants. JavaAn enumeration type is defined by keywords enum. The following is javathe definition of the enumeration type.

public enum Season {
    SPRING, SUMMER, AUTUMN, WINTER;
}

3 features

JavaThe statement defining an enumerated type is concise. It has the following characteristics:

  1. Use keywords enum2) type name, such as here Season3) a string of allowed values, such as the four seasons of spring, summer, autumn and winter defined above 4) enumeration can be defined in a file alone, or embedded in other Javaclasses

In addition to such basic requirements, users have some other options

  1. Enumerations can implement one or more interfaces (Interface) 6) New variables can be defined 7) New methods can be defined 8) Classes that vary according to specific enumeration values ​​can be defined

4 application scenarios

Taking the type safety example mentioned in the background, rewrite that code with an enum type. code show as below:

public enum Season {
    SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4);

    private int code;
    private Season(int code){
        this.code = code;
    }

    public int getCode(){
        return code;
    }
}
public class UseSeason {
    /**
     * 将英文的季节转换成中文季节
     * @param season
     * @return
     */
    public String getChineseSeason(Season season){
        StringBuffer result = new StringBuffer();
        switch(season){
            case SPRING :
                result.append("[中文:春天,枚举常量:" + season.name() + ",数据:" + season.getCode() + "]");
                break;
            case AUTUMN :
                result.append("[中文:秋天,枚举常量:" + season.name() + ",数据:" + season.getCode() + "]");
                break;
            case SUMMER : 
                result.append("[中文:夏天,枚举常量:" + season.name() + ",数据:" + season.getCode() + "]");
                break;
            case WINTER :
                result.append("[中文:冬天,枚举常量:" + season.name() + ",数据:" + season.getCode() + "]");
                break;
            default :
                result.append("地球没有的季节 " + season.name());
                break;
        }
        return result.toString();
    }

    public void doSomething(){
        for(Season s : Season.values()){
            System.out.println(getChineseSeason(s));//这是正常的场景
        }
        //System.out.println(getChineseSeason(5));
        //此处已经是编译不通过了,这就保证了类型安全
    }

    public static void main(String[] arg){
        UseSeason useSeason = new UseSeason();
        useSeason.doSomething();
    }
}

[Chinese: Spring, enumeration constant: SPRING, data: 1] [Chinese: Summer, enumeration constant: SUMMER, data: 2] [Chinese: Autumn, enumeration constant: AUTUMN, data: 3] [Chinese: winter, Enum constant: WINTER, data: 4]

Here's a question, why would I add fields to an enum type? The purpose is to associate data with its constants. For example, 1 represents spring and 2 represents summer.

5 summary

So when should you use enums? Whenever a fixed set of constants is required, such as days of the week, seasons of the year, etc. Or a collection of all the values ​​it contains known before we compile it. The enumeration of Java 1.5 can meet the requirements of most programmers, and its concise and easy-to-use features are very prominent.

6 Usage

Usage 1: Constant

public enum Color {  
  RED, GREEN, BLANK, YELLOW  
}  

Usage 2: switch

enum Signal {  
    GREEN, YELLOW, RED  
}  
public class TrafficLight {  
    Signal color = Signal.RED;  
    public void change() {  
        switch (color) {  
        case RED:  
            color = Signal.GREEN;  
            break;  
        case YELLOW:  
            color = Signal.RED;  
            break;  
        case GREEN:  
            color = Signal.YELLOW;  
            break;  
        }  
    }  
}  

Usage three: Add new methods to the enumeration

public enum Color {  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
    // 普通方法  
    public static String getName(int index) {  
        for (Color c : Color.values()) {  
            if (c.getIndex() == index) {  
                return c.name;  
            }  
        }  
        return null;  
    }  
    // get set 方法  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getIndex() {  
        return index;  
    }  
    public void setIndex(int index) {  
        this.index = index;  
    }  
}  

Usage 4: Override enumeration methods

public enum Color {  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
    //覆盖方法  
    @Override  
    public String toString() {  
        return this.index+"_"+this.name;  
    }  
}  

Usage five: implement the interface

public interface Behaviour {  
    void print();  
    String getInfo();  
}  
public enum Color implements Behaviour{  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
//接口方法  
    @Override  
    public String getInfo() {  
        return this.name;  
    }  
    //接口方法  
    @Override  
    public void print() {  
        System.out.println(this.index+":"+this.name);  
    }  
}  

Usage six: Use interfaces to organize enumerations

public interface Food {  
    enum Coffee implements Food{  
        BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO  
    }  
    enum Dessert implements Food{  
        FRUIT, CAKE, GELATO  
    }  
}

Guess you like

Origin blog.csdn.net/zy_dreamer/article/details/132307486