The article directories

  • Regular use
    • Traverse the enumeration
    • As the judgment condition of the switch
  • Customize properties and methods for enum
  • alternative

Regular use

In Java, a type decorated with the enum keyword is an enumerated type

public enum TypeEnum {
    TYPE_IMAGE,
    TYPE_VIDEO,
}
Copy the code

If the enumeration does not add any methods, the enumeration value defaults to an ordered value starting at 0. Take the TypeEnum enum type for example, whose enumeration constants are in order

TYPE_IMAGE: 0, TYPE_VIDEO: 1

So this code is equivalent to calling Enum(String name, int ordinal) twice, i.e


new Enum<TypeEnum>("TYPE_IMAGE".0);
new Enum<TypeEnum>("TYPE_VIDEO".1);
Copy the code

Traverse the enumeration

for(TypeEnum t:TypeEnum.values()){
	Log.d("TypeEnum".""+t+":"+t.ordinal()+","+t.name());
}
Copy the code

Viewing the Running result

As the judgment condition of the switch

Using enumeration as a switch statement criterion makes our code more readable:

TypeEnum type = TypeEnum.TYPE_IMAGE;
        switch (type) {
            case TYPE_IMAGE:
                Log.d("TypeEnum"."Picture Type");
                break;
            case TYPE_VIDEO:
                Log.d("TypeEnum"."Video Type");
                break;
            default:
                Log.d("TypeEnum"."Type error");
                break;
        }
Copy the code

The results

Customize properties and methods for enum

The constructors of enumerated types are private, so you can’t create them with New, which is why the enumerated data types are safe from change

public enum Color {
    RED("red".1),
    YELLOW("yellow".2),
    BLUE("blue".3);

    private String name;
    private int index;

    Color(String name,int index){
        this.name = name;
        this.index = index;
    }

    public String getName(a) {
        return name;
    }

    public int getIndex(a) {
        returnindex; }}Copy the code
Color color = Color.RED;
        switch (color) {
            case RED:
                Log.d("Color"."Red symbolizes passion."+color.getIndex());
                break;
            case YELLOW:
                Log.d("Color"."Yellow symbolizes vitality."+color.getIndex());
                break;
            case BLUE:
                Log.d("Color"."Blue signifies depth."+color.getIndex());
                break;
            default:
                Log.d("Color"."Colors that don't exist.");
                break;
        }
Copy the code

Here’s another chestnut

public enum LanguageEnum {
    LANGUAGE("language"),
    LANGUAGE_zh("zh"),
    LANGUAGE_en("en");

    private String language;// Custom attributes

    /** constructor, whose enumeration type can only be private */
    LanguageEnum(String language) {
        this.language = language;
    }

    public String getLanguage(a){
        returnlanguage; }}Copy the code
Log.d("TTT"."Language type is"+LanguageEnum.LANGUAGE_zh.getLanguage());
Copy the code

Log output

The language type is zhCopy the code

alternative

They say enumerating fat takes up memory

In fact, Android provides us with an alternative to enumeration — annotation mode (@intdef, @stringdef, @longdef), which is much better than enumeration. Let’s talk about how to use it

First add dependencies

implementation 'com. Android. Support: support - annotations: 28.0.0'
Copy the code
public class MainActivity extends AppCompatActivity {

    // Define constants first
    public static final int SUNDAY = 0;
    public static final int MONDAY = 1;
    public static final int TUESDAY = 2;
    public static final int WEDNESDAY = 3;
    public static final int THURSDAY = 4;
    public static final int FRIDAY = 5;
    public static final int SATURDAY = 6;

     @intdef;
    // @retention defines policies
    // Declare the constructor
    @IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})
    @Retention(RetentionPolicy.SOURCE)
    public @interface WeekDays {}

    @WeekDays int currentDay = SUNDAY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setCurrentDay(WEDNESDAY);

        // Declare variables
        @WeekDays int today = getCurrentDay();

        switch (today){
            case SUNDAY:
                Log.d("TTT"."SUNDAY");
                break;
            case MONDAY:
                Log.d("TTT"."MONDAY");
                break;
            case TUESDAY:
                Log.d("TTT"."TUESDAY");
                break;
            case WEDNESDAY:
                Log.d("TTT"."WEDNESDAY");
                break;
            case THURSDAY:
                Log.d("TTT"."THURSDAY");
                break;
            case FRIDAY:
                Log.d("TTT"."FRIDAY");
                break;
            case SATURDAY:
                Log.d("TTT"."SATURDAY");
                break;
            default:
                break; }}public void setCurrentDay(@WeekDays int currentDay) {
        this.currentDay = currentDay;
    }

    @WeekDays
    public int getCurrentDay(a) {
        returncurrentDay; }}Copy the code

We can write it this way, more or less, but assign values to members when we initialize the annotation class

public class SecondActivity extends AppCompatActivity {

    // Members of annotation classes are public static final by default
    @IntDef({WeekDays.SUNDAY, WeekDays.MONDAY, WeekDays.TUESDAY, WeekDays.WEDNESDAY, WeekDays.THURSDAY, WeekDays.FRIDAY, WeekDays.SATURDAY})
    @Retention(RetentionPolicy.SOURCE)
    public @interface WeekDays {
        int SUNDAY = 0;
        int MONDAY = 1;
        int TUESDAY = 2;
        int WEDNESDAY = 3;
        int THURSDAY = 4;
        int FRIDAY = 5;
        int SATURDAY = 6;
    }

    @WeekDays
    int currentDay = WeekDays.SUNDAY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        setCurrentDay(WeekDays.WEDNESDAY);
        int today = getCurrentDay();

        switch (today) {
            case WeekDays.SUNDAY:
                Log.d("TTT"."SUNDAY");
                break;
            case WeekDays.MONDAY:
                Log.d("TTT"."MONDAY");
                break;
            case WeekDays.TUESDAY:
                Log.d("TTT"."TUESDAY");
                break;
            case WeekDays.WEDNESDAY:
                Log.d("TTT"."WEDNESDAY");
                break;
            case WeekDays.THURSDAY:
                Log.d("TTT"."THURSDAY");
                break;
            case WeekDays.FRIDAY:
                Log.d("TTT"."FRIDAY");
                break;
            case WeekDays.SATURDAY:
                Log.d("TTT"."SATURDAY");
                break; }}public void setCurrentDay(@WeekDays int currentDay) {
        this.currentDay = currentDay;
    }

    @WeekDays
    public int getCurrentDay(a) {
        returncurrentDay; }}Copy the code

@intdef is used to simplify conversion from enumerations to integer values, and @stringdef and @longdef are used for String effects

Java enumeration: small enum, elegant and clean