Article directory
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 enum
defined 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:
-
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.
-
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.
-
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. -
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.
-
Iterability: The enumeration type can
values()
obtain an array containing all enumeration constants through methods, and supportsfor-each
loop traversal. This makes it easy to iterate over and manipulate enumeration constants. -
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.
-
Serialization support: The enumeration type implements
Serializable
the 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, EnumName
is the name of the enumeration type, CONSTANT1
, CONSTANT2
etc. 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 Season
enumeration type named , which contains four enumeration constants: SPRING
, SUMMER
, AUTUMN
and 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 DayOfWeek
contains seven enumeration constants, each of which has a value
field 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 TestEnum
that contains three enumeration constants RED
, GREEN
and 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, TestEnum
the enum class has the following characteristics and code descriptions:
- Enumeration constants:
RED
,GREEN
andBLACK
are three instantiated objects of the enumeration classTestEnum
that 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 examplemain()
usesTestEnum.values()
the method in the method to obtainTestEnum
all 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 constantsordinal()
return their values in the order they are defined in the enumeration type (starting from 0).compareTo()
Method: throughRED.compareTo(BLACK)
andBLACK.compareTo(GREEN)
can compare the order of two enumeration constants and return an integer value.
This example also shows how to main()
use switch
the 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:
-
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.
-
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.
-
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.
-
Avoid magic values: Using enumeration types can avoid hard-coded magic values, providing better code readability and maintainability.
-
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. -
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:
-
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.
-
Not suitable for large data collections: If large data collections need to be represented, constant definitions of enumerated types can become lengthy and cumbersome.
-
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.
-
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.