Application of enumeration type in java

I. Introduction

Why use enum types?

Before that, we need to create a set of integer constants, but these sets of integer constants do not necessarily limit their own values ​​to the range of this constant set, so they are more risky and more difficult to use. However, the enumeration type eliminates this defect and appears to be more useful, as illustrated by the following example.

The public final staticmethod used defines the following set of constants:

public class WeekDay{
    public static final int SUN = 1;
    public static final int MON = 2;
    public static final int TUE = 3;
}

Pass different types of parameters through the following methods:

private static String getToday(int weekDay){
    switch (weekDay){
        case ConstantTest.MON:
            System.out.println("MON");
            break;
        case ConstantTest.SUN:
            System.out.println("SUN");
            break;
        case ConstantTest.TUE:
            System.out.println("TUE");
            break;
    }
    return null;
}

//调用上面的方法
getToday(ConstantTest.MON);//正常的场景
getToday(5);//错误的场景,产生类型不安全的问题,因为取值没有在常量集范围之内

Through the above method, getToday(5)although the passed parameters are passed at compile time, we don't know what happens at runtime, but this is obviously not in line with the type safety of java programs.

2. Enumeration Definition

枚举类型It refers to a legal type composed of a fixed set of constants. The definition method is as follows:

public enum WeekDay{
    SUN, MON, TUE, WED, THT, FRI, SAT
}

When creating an enum, the compiler will automatically add some useful features. It will create a toString() method so that you can easily display the name of an enum instance, and the compiler will also create an ordinal() method to represent a certain enum instance. The declaration order of a specific enum constant, and the static values() method, which is used to generate an array of these constant values ​​in the order in which the enum constants are declared:

for (WeekDay wd :
        WeekDay.values()) {
    System.out.println(wd + ",ordinal" + wd.ordinal());
}

output:
SUN,ordinal:0
MON,ordinal:1
TUE,ordinal:2
WED,ordinal:3
THT,ordinal:4
FRI,ordinal:5
SAT,ordinal:6

Rewrite the above example:

//定义枚举
public enum WeekDay {
    SUN, MON, TUE, WED, THT, FRI, SAT
}

private static String getToday(WeekDay weekDay){
    switch (weekDay){
        case MON:
            System.out.println("MON");
            break;
        case SUN:
            System.out.println("SUN");
            break;
        case TUE:
            System.out.println("TUE");
            break;
    }
    return null;
}

public static void main(String[] args){
    getToday(WeekDay.MON);//正常的场景
    //getToday(5);//编译时出错,超出了enum的类型范围。
}

3. Usage of enumeration

  1. constant definition
public enum WeekDay {
    SUN, MON, TUE, WED, THT, FRI, SAT
}
  1. switch
public enum WeekDay {
    SUN, MON, TUE, WED, THT, FRI, SAT
}

public class SelectDay{
    WeekDay weekday = WeekDay.SUN;
    public void select(){
        switch(weekday){
            case SUN:
                weekday = WeekDay.SUN;
                bread;
            ...
        }
    }
}
  1. Add new method to enum
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;  
    }  
}  
  1. Overriding 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; 
    } 
}
  1. implement 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); 
    } 
}
  1. 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 
    } 
}

Example reference to: http://www.imooc.com/article/3924

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325945050&siteId=291194637