Before Java5, it was common to use a set of expressions like public static final to express status codes and other operations to improve the readability and maintainability of direct hard-coding. However, the expression content is limited, and too much semantic ambiguity can be confusing. So JAVA5 introduced enumerations to do just that.

In Java, a type decorated with the enum keyword is an enumerated type. The form is as follows:

Enum Color {RED, GREEN, BLUE} If the enumeration does not add any methods, the enumeration value defaults to an ordered number starting from 0. Take the Color enumeration type for example, whose enumeration constants are RED: 0, GREEN: 1, and BLUE: 2

Benefits of enumerations: Constants can be organized and managed uniformly.

Typical application scenarios of enumeration include error codes and state machines.

The nature of enumerated types

Although enum may seem like a new data type, it is, in fact, a restricted class with its own methods.

When you create an enum, the compiler generates an associated class for you that inherits from java.lang.enum.

Java. Lang. Enum class declaration

public abstract class Enum<E extends Enum<E>>

implements Comparable<E>, Serializable { … }

Method of enumeration

In enum, some basic methods are provided:

Values () : Returns an array of instances of enum, and the elements in that array remain in the exact order in which they were declared in the enum.

Name () : Returns the instance name.

Ordinal () : Returns the order in which the instance was declared, starting from 0.

GetDeclaringClass () : Returns the enum type to which the instance belongs.

Equals () : Checks whether they are the same object.

Enum instances can be compared using ==.

In addition, java.lang.enum implements the Comparable and Serializable interfaces, so it also provides the compareTo() method.

Example: Show the basic method of enum

public class EnumMethodDemo { enum Color {RED, GREEN, BLUE; } enum Size {BIG, MIDDLE, SMALL; } public static void main(String args[]) { System.out.println("=========== Print all Color ===========");
        for (Color c : Color.values()) {
            System.out.println(c + " ordinal: " + c.ordinal());
        }
        System.out.println("=========== Print all Size ===========");
        for (Size s : Size.values()) {
            System.out.println(s + " ordinal: " + s.ordinal());
        }

        Color green = Color.GREEN;
        System.out.println("green name(): " + green.name());
        System.out.println("green getDeclaringClass(): " + green.getDeclaringClass());
        System.out.println("green hashCode(): " + green.hashCode());
        System.out.println("green compareTo Color.GREEN: " + green.compareTo(Color.GREEN));
        System.out.println("green equals Color.GREEN: " + green.equals(Color.GREEN));
        System.out.println("green equals Size.MIDDLE: " + green.equals(Size.MIDDLE));
        System.out.println("green equals 1: " + green.equals(1));
        System.out.format("green == Color.BLUE: %b\n", green == Color.BLUE); }}Copy the code

The output

=========== Print all Color ===========
RED ordinal: 0
GREEN ordinal: 1
BLUE ordinal: 2
=========== Print all Size ===========
BIG ordinal: 0
MIDDLE ordinal: 1
SMALL ordinal: 2
green name(): GREEN
green getDeclaringClass(): class org.zp.javase.enumeration.EnumDemo$Color
green hashCode(): 460141958
green compareTo Color.GREEN: 0
green equals Color.GREEN: true
green equals Size.MIDDLE: false
green equals 1: false
green == Color.BLUE: false
Copy the code

Features of enumeration

The nature of enumerations boils down to one sentence:

Except that you can’t inherit, you can basically think of enum as a regular class.

But this sentence needs to be broken down to understand. Let’s break it down. Enumerations can add methods. As mentioned in the concepts section, enumerations default to ordered values starting at 0. The problem then is how to assign values to enumeration displays. If you’ve ever worked with C/C++, you’ll naturally think of the assignment symbol =. In C/C++, we can assign values to enum constants using the assignment symbol =. Unfortunately, Java syntax does not allow the use of the assignment symbol = to assign values to enumerated constants.

Example: enumeration declarations in C/C++

typedef enum{
    ONE = 1,
    TWO,
    THREE = 3,
    TEN = 10
} Number;
Copy the code

Enum can add normal methods, static methods, abstract methods, and constructors

While Java cannot assign an instance directly, it has a better solution: add methods to enums to implement explicit assignment indirectly. When you create an enum, you can add multiple methods to it, and you can even add constructors to it. Note one detail: if you define a method for an enum, you must add a semicolon to the end of the last instance of the enum. Also, in enUms, instances must be defined first, and fields or methods cannot be defined before instances. Otherwise, the compiler will report an error. Example: How to define normal methods, static methods, abstract methods, constructors in enumeration

public enum ErrorCode {
    OK(0) {
        public String getDescription() {
            return "Success";
        }
    },
    ERROR_A(100) {
        public String getDescription() {
            return "A wrong";
        }
    },
    ERROR_B(200) {
        public String getDescription() {
            return "Error" B; }}; private int code; Private ErrorCode(int number) {this.code = number; } public intgetCode() {// Common methodreturncode; } public abstract String getDescription(); Public static void main(String args[]) {public static void main(String args[])for (ErrorCode s : ErrorCode.values()) {
            System.out.println("code: " + s.getCode() + ", description: "+ s.getDescription()); }}}Copy the code

Note: The above example is not desirable and is merely intended to show that enumerations support defining various methods. Here is a simplified example

Example: an error code enumeration type definition

The result in this example is the same as that in the preceding example.

public enum ErrorCodeEn {
    OK(0, "Success"),
    ERROR_A(100, "A wrong"),
    ERROR_B(200, "Error" B);

    ErrorCodeEn(int number, String description) {
        this.code = number;
        this.description = description;
    }
    private int code;
    private String description;
    public int getCode() {
        return code;
    }
    public String getDescription() {
        returndescription; } public static void main(String args[]) {// static methodfor (ErrorCodeEn s : ErrorCodeEn.values()) {
            System.out.println("code: " + s.getCode() + ", description: "+ s.getDescription()); }}}Copy the code

Welcome to study and exchange group 569772982, let’s study and exchange together.