[Java] enumeration type


1. Enumeration type

1.1 What is an enumeration type

An enumerated type is a special data type used to define a fixed set of named constants. Enumerated types provide a more powerful, safer, and more readable way to represent a set of related constants.

In Java, enumeration types are enumdefined by using keywords. An enumerated type can contain one or more enumerated constants, each of which is an instance of the enumerated type. Enumeration constants are predefined within an enumeration type, which are unique, named objects .

1.2 Characteristics of enumeration types in Java

The characteristics of enumeration types in Java are as follows:

  1. Finite set of instances: An enumerated type is a finite set of instances, each of which is a unique, named constant of the enumerated type. Instances of enumerated types are predetermined when they are defined and cannot be modified.

  2. Type Safety: Enum types are statically type checked at compile time, which means that the compiler can detect type errors when using enum constants. This provides greater type safety and avoids some common programming mistakes.

  3. Uniqueness and Comparability: Each enumeration constant is unique within the enumeration type and can be ==compared using operators. This makes it possible to use enumeration constants in code for precise comparisons and judgments.

  4. Readability and maintainability: Constants of enumerated types are meaningful, self-describing, and intuitively understand their meaning. This makes the code more readable, understandable and maintainable. At the same time, constants of enumerated types can also provide better documentation and comments.

  5. Iterability: The enumeration type can values()obtain an array containing all enumeration constants through methods, and supports for-eachloop traversal. This makes it easy to iterate over and manipulate enumeration constants.

  6. Support for methods and fields: Enumeration constants can have fields and methods, and specific properties and behaviors can be defined for each constant. This makes it possible to encapsulate related properties and operations inside enumeration constants.

  7. Serialization support: The enumeration type implements Serializablethe interface by default and can be serialized and deserialized. This makes it possible to use enumerated types in scenarios such as network transmission, storage, and persistence.

By taking advantage of enumerated types, fixed collections of named constants can be represented more elegantly and provide better type safety and code readability. They can provide more concise, maintainable and extensible solutions in many scenarios.

Second, the use of enumerated types

2.1 Creating a Grammar

In Java, the syntax for creating an enumeration type is as follows:

enum EnumName {
    
    
    CONSTANT1,
    CONSTANT2,
    // ...
}

Among them, EnumNameis the name of the enumeration type, CONSTANT1, CONSTANT2etc. are the enumeration constants, separated by commas. Each enumeration constant is an instance of the enumeration type and is a unique, named constant object.

Here's an example of creating a simple season enum:

enum Season {
    
    
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER
}

The preceding example creates an Seasonenumeration type named , which contains four enumeration constants: SPRING, SUMMER, AUTUMNand WINTER.

Within an enumerated type, fields and methods can be defined. For example, to define specific properties and behaviors for each enum constant:

enum DayOfWeek {
    
    
    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    private int value;

    private DayOfWeek(int value) {
    
    
        this.value = value;
    }

    public int getValue() {
    
    
        return value;
    }
}

The enumeration type in the preceding example DayOfWeekcontains seven enumeration constants, each of which has a valuefield named and a getValue()method that returns the value of that field.

In this way, it is possible to create enumerated types with specific constants and custom properties and behaviors.

2.2 Common methods

Here are the commonly used methods of enumerated types and what they are used for:

method use
name() Get the name of the enum constant
ordinal() Get the serial number of the enumeration constant
values() Get all enumeration constants in the enumeration type
valueOf(String name) Get the corresponding enumeration constant according to the name of the enumeration constant
toString() Returns the string representation of the enum constant
Custom fields and methods Enumeration constants can have custom fields and methods to provide specific properties and behaviors

These methods are commonly used methods of enumeration types, and can be used to obtain information about enumeration constants, perform comparisons and conversions between enumeration constants, and perform custom operations. The method can be used values()to obtain all enumeration constants in the enumeration type, and perform traversal and processing. valueOf()The method can obtain the corresponding enumeration constant instance according to the name of the enumeration constant.

In addition, custom fields and methods can be defined in the enumeration type to meet specific needs. For example, you can define additional properties, calculation methods, etc. for enumeration constants to extend the functionality of enumeration types.

2.3 Use cases

Create an enumeration class TestEnumthat contains three enumeration constants RED, GREENand BLACK. The following is a description and code analysis of the example enumeration class:

public enum TestEnum {
    
    
    RED("RED", 1),
    GREEN("GREEN", 2),
    BLACK("BLACK", 3);

    private String color;
    private int ori;

    // 构造方法
    private TestEnum(String color, int ori) {
    
    
        this.color = color;
        this.ori = ori;
    }

    // 主方法
    public static void main(String[] args) {
    
    
        TestEnum[] values = TestEnum.values();
        for (TestEnum value : values) {
    
    
            System.out.println(value + " ori: " + value.ordinal());
        }

        System.out.println("======================");

        System.out.println(TestEnum.valueOf("RED"));
        System.out.println("======================");
        System.out.println(RED.compareTo(BLACK));
        System.out.println(BLACK.compareTo(GREEN));
    }
}

In this example, TestEnumthe enum class has the following characteristics and code descriptions:

  • Enumeration constants: RED, GREENand BLACKare three instantiated objects of the enumeration class TestEnumthat are unique, named constants.
  • Construction method: The construction method of the enumeration class is private by default and can only be used inside the enumeration class. In this example, a private constructor is used to set the corresponding color and primitive value for each enumeration constant.
  • values()Method: This example main()uses TestEnum.values()the method in the method to obtain TestEnumall the enumeration constants in the enumeration class, and perform traversal output.
  • valueOf(String name)TestEnum.valueOf("RED")Method: You can get the enumeration object whose enumeration constant name is "RED" through .
  • ordinal()Methods: The methods of enumeration constants ordinal()return their values ​​in the order they are defined in the enumeration type (starting from 0).
  • compareTo()Method: through RED.compareTo(BLACK)and BLACK.compareTo(GREEN)can compare the order of two enumeration constants and return an integer value.

This example also shows how to main()use switchthe statement in the method to perform different logic based on the value of the enumeration constant.

Three, the advantages and disadvantages of enumeration

Enum types have the following advantages and disadvantages in Java:

advantage:

  1. Readability and maintainability: Constants in enumerated types are meaningful and self-describing, making code more readable, understandable, and maintainable. Enum constants have unique names, providing better documentation and comments.

  2. Type safety: Enumeration types are statically type checked at compile time, which means that the compiler can ensure that only valid enumeration constants are used, providing higher type safety.

  3. A limited set of values: The enumeration type defines a limited set of values, limiting the range of valid values. This can help avoid invalid or unexpected values ​​in your program.

  4. Avoid magic values: Using enumeration types can avoid hard-coded magic values, providing better code readability and maintainability.

  5. Enhanced compiler support: The enumeration type provides some additional support at the compiler level, such as automatically adding common methods (such as , values()) valueOf(), the order of enumeration constants, etc.

  6. Good for representing states and options: Enumerated types are great for representing states, options, and fixed sets like seasons, colors, days of the week, and so on.

shortcoming:

  1. Not suitable for dynamically changing data: enumerated types are defined at compile time, and their constant set is fixed. If you need to represent a dynamically changing collection of data, an enumerated type may not be suitable.

  2. Not suitable for large data collections: If large data collections need to be represented, constant definitions of enumerated types can become lengthy and cumbersome.

  3. Lack of extensibility: The constants of the enumeration type are determined at compile time, and dynamic addition or deletion of constants is not supported. Therefore, if the constant set needs to be modified frequently, it may lead to code changes and increased maintenance costs.

  4. Inheritance is not supported: enumeration types do not support inheritance, and the inheritance relationship between enumeration types cannot be realized.

All in all, enumerated types are very useful in many scenarios, especially for representing states, options, and fixed collections. They provide benefits such as type safety, readability, and maintainability. However, enumerated types may not be the best choice for dynamically changing data collections or large data collections, and for situations where frequent modification of constant collections is required.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/131621143