Java enum usage details and example code

  • 2020-06-12 08:55:36
  • OfStack

Use of Java enum

Usage 1: Constant

Before JDK1.5, we defined the constants as: public static fianl... . Now that you have enumerations, you can group related constants into an enumeration type, and enumerations provide more methods than constants.


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

Usage 2: switch

The switch statement before JDK1.6 only supports int,char,enum types. Enumeration makes 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 a new method to an enumeration

If you want to customize your methods, you must add a semicolon at the end of the enum instance sequence. And Java requires that an enum instance 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;

    //  A constructor 
    private Color(String name, int index) {
      this.name = name;
      this.index = index;
    }

    //  Common 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 the method of enumeration

An example of toString() method override is given below.


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;

    //  A constructor 
    private Color(String name, int index) {
      this.name = name;
      this.index = index;
    }

    //  Override method 
    @Override
    public String toString() {
      return this.index + "_" + this.name;
    }
  }

  public static void main(String[] args) {
    System.out.println(Color.RED.toString());
  }
}

Usage 5: Implement the interface

All enumerations are inherited from the ES43en.lang.Enum class. Because Java does not support multiple inheritance, enumeration objects cannot 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;

    //  A constructor 
    private Color(String name, int index) {
      this.name = name;
      this.index = index;
    }

    //  Interface methods 

    @Override
    public String getInfo() {
      return this.name;
    }

    //  Interface methods 
    @Override
    public void print() {
      System.out.println(this.index + ":" + this.name);
    }
  }

Use 6: Organize enumerations using interfaces


public interface Food {
    enum Coffee implements Food {
      BLACK_COFFEE, DECAF_COFFEE, LATTE, CAPPUCCINO
    }

    enum Dessert implements Food {
      FRUIT, CAKE, GELATO
    }
  }

Usage 7: About the use of enumerated collections

java. util. EnumSet and java. util. EnumMap are two enumeration sets. EnumSet ensures that elements in the set do not repeat; key in EnumMap is of type enum, while value can be any type. The use of these two collections will not be covered here, but refer to the JDK documentation

The difference between enumerations and constant definitions

1. Constant methods are usually defined

We usually use the method public final static to define the code as follows: 1 for red light, 3 for green light and 2 for yellow light.


public class Light {
    /*  A red light  */
    public final static int RED = 1;

    /*  A green light  */
    public final static int GREEN = 3;

    /*  Yellow light  */
    public final static int YELLOW = 2;
  }

2. Enumeration types define constant methods

The simple way to define an enumerated type is as follows. It seems that there is no way to define the value of each enumerated type. For example, our code for defining red, green, and yellow lights might look like this:


public enum Light {
    RED, GREEN, YELLOW;
  }

We can only represent red, green, and yellow lights, but we can't represent specific values. Don't worry, since enumerated types provide constructors, we can do this with constructors and override toString methods. First, add a constructor to the Light enumeration type, then pass the value of each enumeration type into the corresponding parameter through the constructor, and overwrite the toString method, in which the parameter passed from the constructor is returned. The modified code is as follows:


public enum Light {

  //  Use the constructor to pass arguments 
  RED(1), GREEN(3), YELLOW(2);

  //  Define private variables 
  private int nCode;

  //  Constructor, enumeration types can only be private 
  private Light(int _nCode) {

    this.nCode = _nCode;

  }

  @Override
  public String toString() {

    return String.valueOf(this.nCode);

  }

}

3. Complete sample code

The complete demo code for the enumerated type is as follows:


public class LightTest {

  // 1. Define enumerated types 

  public enum Light {

    //  Use the constructor to pass arguments 

    RED(1), GREEN(3), YELLOW(2);

    //  Define private variables 

    private int nCode;

    //  Constructor, enumeration types 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 enumerated types 

    System.out.println(" Demonstrates traversal of enumerated types  ......");

    testTraversalEnum();

    // 2. demo EnumMap Use of objects 

    System.out.println(" demo EnmuMap Object usage and traversal .....");

    testEnumMap();

    // 3. demo EnmuSet The use of 

    System.out.println(" demo EnmuSet Object usage and traversal .....");

    testEnumSet();

  }

  /**
   * 
   *  Demonstrates traversal of enumerated types 
   */

  private static void testTraversalEnum() {

    Light[] allLight = Light.values();

    for (Light aLight : allLight) {

      System.out.println(" The current light name : " + aLight.name());

      System.out.println(" The current light ordinal : " + aLight.ordinal());

      System.out.println(" Current lamp: " + aLight);

    }

  }

  /**
   * 
   *  demo EnumMap The use of EnumMap with HashMap The use of the same, but key If it's an enumerated type 
   */

  private static void testEnumMap() {

    // 1. Demonstrate the definition EnumMap Object, EnumMap The constructor of the object needs arguments passed in , The default is key The type of the class 

    EnumMap<Light, String> currEnumMap = new EnumMap<Light, String>(

    Light.class);

    currEnumMap.put(Light.RED, " A red light ");

    currEnumMap.put(Light.GREEN, " A green light ");

    currEnumMap.put(Light.YELLOW, " Yellow light ");

    // 2. Traverse object 

    for (Light aLight : Light.values()) {

      System.out.println("[key=" + aLight.name() + ",value="

      + currEnumMap.get(aLight) + "]");

    }

  }

  /**
   * 
   *  demo EnumSet How to use it, EnumSet is 1 Abstract class, get 1 Enumeration type content for three types <BR/>
   * 
   *  You can use allOf methods 
   */

  private static void testEnumSet() {

    EnumSet<Light> currEnumSet = EnumSet.allOf(Light.class);

    for (Light aLightSetElement : currEnumSet) {

      System.out.println(" The current EnumSet , the data are: " + aLightSetElement);

    }

  }

}

The execution results are as follows:

Demonstration of enumeration type traversal...

Current lamp name: RED

Current lamp ordinal: 0

Current light: 1

Current lamp name: GREEN

Current lamp ordinal: 1

Current light: 3

Current lamp name: YELLOW

Current lamp ordinal: 2

Current light: 2

Demonstrates the use and traversal of EnmuMap objects...

[key = RED, value = red]

[key = GREEN, value = green]

The yellow light] [key = YELLOW, value =

Demonstrates 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

4. The usual difference between defining constant methods and enumerating defining constant methods

The following may be boring, but it's definitely worth a peek

1. The code:


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

0

What's wrong with it? Everyone has been using it for a long time. There's no problem.

First, it's not type safe. You have to make sure it's int

And second, you have to make sure that the range is 0 and 1

And in the end, a lot of times when you print it out, you only see 1's and 0's,

But the person who doesn't see the code doesn't know what you're trying to do, get rid of all your old public static final constants

2. You can create an enum class and treat it as a normal class. Except it can't inherit from any other class. (java is a single inheritance, it has inherited Enum),

You can add other methods that override its own methods

3. The switch() parameter is ready to use enum

4. The values() method is the static method that the compiler inserts into the enum definition, so when you turn an enum instance up to the parent class Enum is, values() becomes unreachable. Solution: There is one 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. Cannot subclass from enum. If you need to extend the elements in enum, create an enumeration inside one interface that implements the interface to group the elements. To group enumeration elements.

6. Use EnumSet instead of logo. enum requires its members to be unique, but the addition element cannot be removed from enum.

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

enum allows programmers to write methods for eunm instances. Therefore, each enum instance can be assigned a different behavior.

9. Chain of responsibility using enum (Chain of Responsibility). This chain of responsibility pattern relates to design patterns. Solve a problem in many different ways. Then link them up to 1. When a request arrives, the chain is traversed until a solution in the chain can handle the request.

10. Use the enum state machine.

11. Use enum multiplexing.

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


Related articles: