Java (enum) enumeration usage details

  • 2020-05-17 05:34:58
  • OfStack

concept

The full name of enum is called enumeration and is a new feature introduced in JDK 1.5.

In Java, the type modified by the enum keyword is the 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 value starting at 0. Take the example of an Color enumeration type, whose enumeration constants are RED: 0, GREEN: 1, BLUE: 2, respectively

Benefits of enumeration: you can organize constants and manage them with 1.

Typical application scenarios of enumeration: error codes, state machines, etc.

The nature of enumerated types

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

When you create enum, the compiler will generate a related class for you, which inherits from java.lang.Enum .

The < code > java. lang. Enum < / code > class declaration


public abstract class Enum<E extends Enum<E>>
    implements Comparable<E>, Serializable { ... }

Enumeration method

In enum, some basic methods are provided:

values() : returns an array of enum instances in exactly the order in which they were declared in enum.

name() : returns the instance name.

ordinal() : returns the order in which the instance was declared, starting at 0.

getDeclaringClass() : returns the type of enum to which the instance belongs.

equals() : determine whether the same object is present.

You can use == to compare instances of enum.

In addition, the java.lang.Enum implements the Comparable and Serializable interfaces, so the compareTo() method is also provided.

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);
  }
}

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

Properties of enumeration

Enumeration features, boil down to 1 sentence:

Except for the fact that you can't inherit, you can basically view enum as a regular class.

But this sentence needs to be broken down to understand, let us elaborate.

Enumerations can add methods

As mentioned in the concepts section, enumeration values default to ordered values starting at 0. The question then arises: how to assign values to the enumeration displays.

Java does not allow enum constants to be assigned using =

If you have been exposed to C/C++, you will naturally think of the assignment symbol = . In the C/C++ language, enum can be assigned to enumeration constants using the assignment symbol =; Unfortunately, the assignment symbol = is not allowed in the Java syntax to assign values to enumeration constants.

Example: enumeration declarations in C/C++ language


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

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

While Java cannot assign values to instances directly, it has a better solution: add methods to enum to indirectly display assignments.

When you create enum , you can add multiple methods to it, and you can even add constructors to it.

Note one detail: if you want to define a method for enum, you must add a semicolon at the end of the last instance of enum. In addition, in enum, you must define the instance first, and you cannot define fields or methods before the instance. Otherwise, the compiler will report an error.

Example: fully demonstrate how to define normal methods, static methods, abstract methods, constructors in an enumeration


public enum ErrorCode {
  OK(0) {
    public String getDescription() {
      return " successful ";
    }
  },
  ERROR_A(100) {
    public String getDescription() {
      return " error A";
    }
  },
  ERROR_B(200) {
    public String getDescription() {
      return " error B";
    }
  };

  private int code;
  
  //  Construction method: enum Can only be declared as private Permission or undeclared permission 
  private ErrorCode(int number) { //  A constructor 
    this.code = number;
  }
  public int getCode() { //  Common methods 
    return code;
  } //  Common methods 
  public abstract String getDescription(); //  Abstract methods 
  public static void main(String args[]) { //  A static method 
    for (ErrorCode s : ErrorCode.values()) {
      System.out.println("code: " + s.getCode() + ", description: " + s.getDescription());
    }
  }
}

Note: the above example is not desirable, merely to show that enumeration supports defining various methods. Here is a simplified example

Example: definition of an enumeration type of an error code

The result of this example and the previous example are exactly the same.


public enum ErrorCodeEn {
  OK(0, " successful "),
  ERROR_A(100, " error A"),
  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() {
    return description;
  }
  public static void main(String args[]) { //  A static method 
    for (ErrorCodeEn s : ErrorCodeEn.values()) {
      System.out.println("code: " + s.getCode() + ", description: " + s.getDescription());
    }
  }
}

Enums can implement interfaces

enum can implement the interface like class 1.

Also implementing the error code enumeration class in the previous section, you can constrain its methods by implementing the interface.


public interface INumberEnum {
  int getCode();
  String getDescription();
}

public enum ErrorCodeEn2 implements INumberEnum {
  OK(0, " successful "),
  ERROR_A(100, " error A"),
  ERROR_B(200, " error B");

  ErrorCodeEn2(int number, String description) {
    this.code = number;
    this.description = description;
  }
  
  private int code;
  private String description;

  @Override
  public int getCode() {
    return code;
  }

  @Override
  public String getDescription() {
    return description;
  }
}

Enumerations cannot be inherited

enum cannot inherit another class, and of course, it cannot inherit another enum.

Because enum actually inherits from java.lang.Enum class, and Java does not support multiple inheritance, enum cannot inherit from other classes, and certainly cannot inherit from another enum.

Enumeration of application scenarios

Group constants

Until JDK 1.5, the constant defined in Java is public static final TYPE a; It looks like this. With enums, you can organize related constants to make your code easier to read, more secure, and use the methods that enums provide.

The format of the enumeration declaration

Note: if no method is defined in the enumeration, you can also add a comma, semicolon, or nothing after the last instance.

The following three declarations are equivalent:


enum Color { RED, GREEN, BLUE }
enum Color { RED, GREEN, BLUE, }
enum Color { RED, GREEN, BLUE; }

switch state machine

We often use the switch statement to write state machines. Since JDK7, switch has supported parameters of type int, char, String, enum . The switch code using enumeration is more readable than the parameters of these types.


enum Signal {RED, YELLOW, GREEN}

public static String getTrafficInstruct(Signal signal) {
  String instruct = " Signal failure ";
  switch (signal) {
    case RED:
      instruct = " stop ";
      break;
    case YELLOW:
      instruct = " Yellow light, please ";
      break;
    case GREEN:
      instruct = " The green line ";
      break;
    default:
      break;
  }
  return instruct;
}

Organize the enumeration

Enumerations of similar types can be organized through interfaces or classes.

But 1 is generally organized as an interface.

The reason is that the Java interface automatically adds the public static modifier to the enum type when compiled. The Java class is automatically compiled as enum type with the static modifier. See the difference? That's right, so if you organize enum in a class, if you don't modify it to public, you can only access it in this package.

Example: organize enum in an interface


public abstract class Enum<E extends Enum<E>>
    implements Comparable<E>, Serializable { ... }
0

Example: organize enum in a class

This example has the same effect as the previous one.


public abstract class Enum<E extends Enum<E>>
    implements Comparable<E>, Serializable { ... }
1

Strategy enumeration

One policy enumeration is shown in EffectiveJava. This enumeration classifies enumeration constants by means of enumeration nested enumeration.

This is less concise than switch, but more secure and flexible.

Example: the policy enumeration example in EffectvieJava


public abstract class Enum<E extends Enum<E>>
    implements Comparable<E>, Serializable { ... }
2

test


System.out.println(" Hourly wage 100 In the week 5 work 8 Hourly income: " + PayrollDay.FRIDAY.pay(8.0, 100));
System.out.println(" Hourly wage 100 In the week 6 work 8 Hourly income: " + PayrollDay.SATURDAY.pay(8.0, 100));

EnumSet and EnumMap

Two utility classes are available in Java for easy operation of enum -- EnumSet and EnumMap.

EnumSet is a high-performance implementation of Set for enumerated types. It requires that the enumeration constants put into it must be of the same 1 enumeration type.

EnumMap is an Map implementation tailored specifically for enumerated types. While using the other < code > Map < / code > implementation (such as HashMap) can complete enumeration instance to worth mapping, but using EnumMap will be more efficient: it can only receive the same instance as the key value of an enum type to 1, and due to the number of instances of enumerated types relatively fixed and limited, so EnumMap an enum type to use an array to store and the corresponding values. This makes the EnumMap very efficient.


public abstract class Enum<E extends Enum<E>>
    implements Comparable<E>, Serializable { ... }
4

Related articles: