Detailed explanation of the values() method of the enumeration class enum in Java

Detailed explanation of the values() method of the enumeration class enum in Java

Introduction:

A special method in the enumeration, values(), cannot be found in the API documentation of Enum. When clicking values(), it will also jump to this class.
This method can be understood as: convert the enumeration class into an array of enumeration type, because there is no subscript in the enumeration, we have no way to quickly find the enumeration class we need through the subscript, at this time, after converting to an array, We can find the enumeration class we need through the subscript of the array. The code is shown next.

Example:

public enum EnumText {
    
    
    CODE_TYPE_ONE("春天",1),

    CODE_TYPE_TWO("夏天",2),

    ERROR("数据错误",-1)

    ;

    private String label;
    private Integer value;

    EnumText(String label, Integer value) {
    
    
        this.label = label;
        this.value = value;
    }

    public Integer getValue() {
    
    
        return value;
    }

    public String getLabel() {
    
    
        return label;
    }
}
Test Case:
public class Client {
    
    
    public static void main(String[] args) {
    
    
        for (EnumText e:EnumText.values()){
    
    
            System.out.println(e);
        }
        System.out.println("-------------------------------------");
        for (EnumText e:EnumText.values()){
    
    
            System.out.println(e.getLabel());
        }
        System.out.println("-------------------------------------");
        for (EnumText e:EnumText.values()){
    
    
            System.out.println(e.getValue());
        }
    }
}
Test Results:
CODE_TYPE_ONE
CODE_TYPE_TWO
ERROR
-------------------------------------
春天
夏天
数据错误
-------------------------------------
1
2
-1

The reason why it can be written like this is because values ​​can convert Enum into an array and then traverse it.

Why is there values()

  1. Open the console cmd and enter the file directory to be compiled
  2. Compile the .java file
  3. Decompile the successfully compiled .class file
//将.java文件编译
javac EnumText.java

//将编译成功后的.class文件反编译
javap -c EnumText.class >e.txt

After opening the e.txt file, you can see

image-20230406155839102

The compiler has automatically inserted the **values()** method for us

Summarize

1. If the enum keyword is used to declare an enumeration class, the declared enumeration class inherits the Enum class by default, and the bottom layer is a final class by default .

2. When writing a custom enum , which does not contain the values() method , when compiling the java file, the java compiler will automatically help us generate this method

Guess you like

Origin blog.csdn.net/qq_48778364/article/details/129991963