English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Introduction and Example Code of Java enum Usage

Usage of Java enum

Usage 1: Constants

In JDK1.5 Previously, we defined constants as: public static final.... Now, with enums, we can group related constants into an enum type, and enums provide more methods than constants.

public enum Color { 
 RED, GREEN, BLANK, YELLOW 
} 

Usage 2: switch

JDK1.6The previous switch statement only supports int, char, and enum types. Using enums can make our code more readable.

enum Signal {
    GREEN, YELLOW, RED
  }
  public class TrafficLight {
    Signal color = Signal.RED;
    public void change() {}}
      switch (color) {
      case RED:
        color = Signal.GREEN;
        break;
      case YELLOW:
        color = Signal.RED;
        break;
      case GREEN:
        color = Signal.YELLOW;
        break;
      }
    }
  }

Usage 3: Add new methods to the enum

If you plan to customize your own methods, you must add a semicolon at the end of the enum instance sequence. And Java requires that enum instances must be defined first.

public enum Color {
    RED("red", 1), GREEN("green", 2), BLANK("white", 3), YELLO("yellow", 4);
    // member variables
    private String name;
    private int index;
    // Constructor Method
    private Color(String name, int index) {
      this.name = name;
      this.index = index;
    }
    // Normal methods
    public static String getName(int index) {
      for (Color c : Color.values()) {
        if (c.getIndex() == index) {
          return c.name;
        }
      }
      return null;
    }
    // get set methods
    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;
    }
  }

Usage 4: Override enum methods

Below is an example of overriding the toString() method.

public class Test {
  public enum Color {
    RED("red", 1), GREEN("green", 2), BLANK("white", 3), YELLO("yellow", 4);
    // member variables
    private String name;
    private int index;
    // Constructor Method
    private Color(String name, int index) {
      this.name = name;
      this.index = index;
    }
    // Override methods
    @Override
    public String toString() {
      return this.index + "_" + this.name;
    }
  }
  public static void main(String[] args) {
    System.out.println(Color.RED.toString());
  }
}

Usage 5: Implement an interface

All enums inherit from the java.lang.Enum class. Since Java does not support multiple inheritance, enum objects can no longer inherit from other classes.

public interface Behaviour {
    void print();
    String getInfo();
  }
  public enum Color implements Behaviour {
    RED("red", 1), GREEN("green", 2), BLANK("white", 3), YELLO("yellow", 4);
    // member variables
    private String name;
    private int index;
    // Constructor Method
    private Color(String name, int index) {
      this.name = name;
      this.index = index;
    }
    // Interface Method
    @Override
    public String getInfo() {
      return this.name;
    }
    // Interface Method
    @Override
    public void print() {
      System.out.println(this.index + :" + this.name);
    }
  }

Use Case Six: Using Interfaces to Organize Enumerations

public interface Food {
    enum Coffee implements Food {
      BLACK_COFFEE, DECAF_COFFEE, LATTE, CAPPUCCINO
    }
    enum Dessert implements Food {
      FRUIT, CAKE, GELATO
    }
  }

Use Case Seven: About the Use of Enumeration Collections

java.util.EnumSet and java.util.EnumMap are two enumeration collections. EnumSet ensures that the elements in the collection are not repeated; in EnumMap, the key is of enum type, and the value can be of any type. The use of these two collections is not elaborated here, please refer to the JDK documentation

Difference between Enumeration and Constant Definition

Part One: Common Definition Method of Constants

We usually define the code using public final static methods as follows, using1Represents red light,3Represents green light,2Represents yellow light.

public class Light {
    /* Red Light */
    public final static int RED = 1;
    /* Green Light */
    public final static int GREEN = 3;
    /* Yellow Light */
    public final static int YELLOW = 2;
  }

Part Two: Definition Method of Enumeration Constants

The simple definition method of enumeration types is as follows, it seems that we can't define the value of each enumeration type. For example, the code we define for red, green, and yellow lights may be as follows:

public enum Light {
    RED, GREEN, YELLOW;
  }

We can only represent red, green, and yellow lights, but we can't express the specific values. Don't worry, since the enumeration type provides a constructor, we can implement it through the constructor and override the toString method. First, add a constructor to the Light enumeration type, then pass the corresponding parameters to each enumeration type value through the constructor, and at the same time, override the toString method, returning the parameters passed from the constructor in this method. The modified code is as follows:

public enum Light {
  // 
  13), YELLOW(2);
  // Define private variables
  private int nCode;
  // Constructor, the enum type can only be private
  private Light(int _nCode) {
    this.nCode = _nCode;
  }
  @Override
  public String toString() {
    return String.valueOf(this.nCode);
  }
}

Three, complete example code

The complete demonstration code for the enum type is as follows:

public class LightTest {
  // 1.Define enum type
  public enum Light {
    // 
    13), YELLOW(2);
    // Define private variables
    private int nCode;
    // Constructor, the enum type can only be private
    private Light(int _nCode) {
      this.nCode = _nCode;
    }
    @Override
    public String toString() {
      return String.valueOf(this.nCode);
    }
  }
  /**
   * 
   * @param args
   */
  public static void main(String[] args) {
    // 1.Traversal of enum types
    System.out.println("Demonstrates the traversal of enum types ......");
    testTraversalEnum();
    // 2.Demonstrates the use of EnumMap object
    System.out.println("Demonstrates the use and traversal of EnmuMap objects.....");
    testEnumMap();
    // 3.Demonstrates the use of EnmuSet
    System.out.println("Demonstrates the use and traversal of EnmuSet objects.....");
    testEnumSet();
  }
  /**
   * 
   * Demonstrates the traversal of enum types
   */
  private static void testTraversalEnum() {
    Light[] allLight = Light.values();
    for (Light aLight : allLight) {
      System.out.println("Current light name: ", + aLight.name());
      System.out.println("Current light ordinal: ", + aLight.ordinal());
      System.out.println("Current light: ", + aLight);
    }
  }
  /**
   * 
   * Demonstrates the use of EnumMap, the use of EnumMap is similar to that of HashMap, except that the key must be of enum type
   */
  private static void testEnumMap() {
    // 1Demonstrates the definition of an EnumMap object, the constructor of the EnumMap object requires a parameter to be passed in, the default is the type of the key's class
    EnumMap<Light, String> currEnumMap = new EnumMap<Light, String>(}
    Light.class);
    currEnumMap.put(Light.RED, "红灯");
    currEnumMap.put(Light.GREEN, "绿灯");
    currEnumMap.put(Light.YELLOW, "黄灯");
    // 2. Traverse objects
    for (Light aLight : Light.values()) {
      System.out.println("[key=" + aLight.name() + ",value="
      + currEnumMap.get(aLight) + "];
    }
  }
  /**
   * 
   * Demonstration of how to use EnumSet, EnumSet is an abstract class, obtaining the enumeration type content of a type<BR/>
   * 
   * The allOf method can be used
   */
  private static void testEnumSet() {
    EnumSet<Light> currEnumSet = EnumSet.allOf(Light.class);
    for (Light aLightSetElement : currEnumSet) {
      System.out.println("The current EnumSet data is:", + aLightSetElement);
    }
  }
}

The execution result is as follows:

Demonstration of the traversal of enumeration types......

Current light name: RED

Current light ordinal: 0

Current light:1

Current light name: GREEN

Current light ordinal:1

Current light:3

Current light name: YELLOW

Current light ordinal:2

Current light:2

Demonstration of the use and traversal of EnmuMap objects.....

[key=RED,value=Red Light]

[key=GREEN,value=Green Light]

[key=YELLOW,value=Yellow Light]

Demonstration of the use and traversal of EnmuSet objects.....

The current data in EnumSet is:1

The current data in EnumSet is:3

The current data in EnumSet is:2

Chapter 4: The difference between defining constants by methods and defining constants by enumerations

The following content may be a bit boring, but it is definitely worth a look.

1. Code:

public class State {
public static final int ON = ; 1;
public static final Int OFF= 0;
}

What's wrong with it, everyone has been using it like this for a long time, and there's no problem with it.

Firstly, it is not type-safe. You must ensure that it is int

Secondly, you also need to ensure that its range is 0 and1

Finally, many times when you print it out, you only see 1 and 0 ,

But those who haven't seen the code don't know your intention, discard all your old public static final constants

2. You can create an enum class, and treat it as a regular class. The only difference is that it cannot inherit other classes. (Java is single inheritance, it has already inherited Enum),

Other methods can be added, overriding its own methods

3. The switch() parameter can use enum

4. The values() method is a static method inserted by the compiler into the enum definition, so when you upcast an enum instance to a parent class Enum, values() is not accessible. Solution: There is a getEnumConstants() method in Class, so even if there is no values() method in the Enum interface, we can still get all enum instances through the Class object

5. You cannot inherit subclasses from enum. If you need to extend elements in enum, create an enum that implements the interface inside an interface, thereby grouping elements. This achieves the grouping of enum elements.

6. Use EnumSet instead of flags. Enums require that their members are unique, but elements cannot be added or removed from enums.

7. The key of EnumMap is enum, and the value is any other Object object.

8. Enums allow programmers to write methods for enum instances. Therefore, each enum instance can be assigned different behaviors.

9. Use enum's Chain of Responsibility. This is related to the Chain of Responsibility design pattern. Solve a problem in multiple different ways, then link them together. When a request comes in, traverse the chain until a solution in the chain can handle the request.

10. Use enum state machine.

11. Use enum for multi-way dispatch.

 Thank you for reading, I hope it can help everyone, thank you for your support to this site!

You May Also Like