concept
The full name of enum is enumeration, which is a new feature introduced in JDK 1.5.
In Java, the type modified by enum keyword is the enum type. The form is as follows:
enum Color { RED, GREEN, BLUE }If the enum does not add any method, the enum value defaults to an ordered value starting from 0. Taking the Color enumeration type as an example, its enumeration constants are RED: 0, GREEN: 1, and BLUE: 2 in sequence
The benefits of enumeration: constants can be organized and managed in a unified manner.
Typical application scenarios for enumeration: error codes, state machines, etc.
The nature of enumeration types
Although enum looks like a new data type, in fact, enum is a restricted class and has its own method.
When creating an enum, the compiler will generate a related class for you, which is inherited from java.lang.Enum .
java.lang.Enum class declaration
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable { ... }Methods of enumeration
In enum, some basic methods are provided:
values() : Returns an array of enum instances, and the elements in this array are strictly maintained in the order they are declared in enum.
name() : Returns the instance name.
ordinal() : Returns the order when the instance is declared, starting from 0.
getDeclaringClass() : Returns the enum type to which the instance belongs.
equals() : determines whether it is the same object.
You can use == to compare enum instances.
In addition, java.lang.Enum implements the Comparable and Serializable interfaces, so the compareTo() method is also provided.
Example: Basic methods of showing 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.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); }}Output
==============================RED ordinal: 0GREEN ordinal: 1BLUE ordinal: 2=============== Print all Size ================BIG ordinal: 0MIDDLE ordinal: 1SMALL ordinal: 2green name(): GREENgreen getDeclaringClass(): class org.zp.javase.enumeration.EnumDemo$Colorgreen hashCode(): 460141958green compareTo Color.GREEN: 0green equals Color.GREEN: truegreen equals Size.MIDDLE: false equals 1: false == Color.BLUE: false
Features of enumeration
The characteristics of enumeration are summed up in one sentence:
In addition to being unable to inherit, enum can basically be regarded as a regular class.
But this sentence needs to be understood separately, let us explain it in detail.
Enumeration can add methods
In the concept chapter, the enum value defaults to an ordered value starting from 0. Then the question is: how to assign values to the enum displayed.
Java does not allow the use of = assign values to enum constants
If you have been exposed to C/C++, you will definitely think of assignment symbol = naturally. In C/C++ language, the enum can be assigned to enum constants with the assignment symbol = displayed; however, unfortunately, the assignment symbol = assigned to enum constants is not allowed in Java syntax.
Example: Enumeration declaration in C/C++ language
typedef enum{ ONE = 1, TWO, THREE = 3, TEN = 10} Number;enum can add ordinary methods, static methods, abstract methods, and constructor methods.
Although Java cannot directly assign values to instances, it has an even better solution: add methods to enum to indirectly implement display assignments.
When creating enum , you can add multiple methods to it, and even constructors to it.
Note one detail: If you want to define a method for an enum, you must add a semicolon at the end of the last instance of the enum. In addition, in enum, the instance must be defined first, and fields or methods cannot be defined before the instance. Otherwise, the compiler will report an error.
Example: Fully show how to define ordinary methods, static methods, abstract methods, and construct methods in enumerations
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; // Constructor: The constructor of enum can only be declared as private permission or does not declare permission private ErrorCode(int number) { // Constructor this.code = number; } public int getCode() { // Ordinary method return code; } // Ordinary method public abstract String getDescription(); // Abstract method public static void main(String args[]) { // Static method for (ErrorCode s: ErrorCode.values()) { System.out.println("code: " + s.getCode() + ", description: " + s.getDescription()); } }}Note: The above example is not advisable, just to show that enumeration supports the definition of various methods. Here is a simplified example
Example: Definition of an error code enumeration type
The execution results of this example and the above example are exactly the same.
public enum ErrorCodeEn { OK(0, "Success"), 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[]) { // Static method for (ErrorCodeEn s: ErrorCodeEn.values()) { System.out.println("code: " + s.getCode() + ", description: " + s.getDescription()); } }}Enumeration can implement interfaces
enum can implement interfaces like general classes.
It also implements the error code enumeration class in the previous section. By implementing the interface, it can constrain its methods.
public interface INumberEnum { int getCode(); String getDescription();}public enum ErrorCodeEn2 implements INumberEnum { OK(0, "Success"), 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; }}Enumeration cannot be inherited
enum cannot inherit another class, and of course, it cannot inherit another enum.
Because enum are actually inherited from java.lang.Enum class, and Java does not support multiple inheritance, enum cannot inherit other classes, and of course it cannot inherit another enum .
Enumerated application scenarios
Organize constants
Before JDK1.5, the definition of constants in Java was public static final TYPE a ; in this form. With enumerations, you can organize constants of associations to make the code more readable and safe, and also use the methods provided by enumerations.
Enumeration declaration format
Note: If there is no method defined in the enum, you can also add a comma, semicolon or nothing after the last instance.
The following three declaration methods are equivalent:
enum Color { RED, GREEN, BLUE }enum Color { RED, GREEN, BLUE, }enum Color { RED, GREEN, BLUE; }switch state machine
We often use switch statements to write state machines. After JDK7, switch has supported parameters of int、char、String、enum types. Compared with these types of parameters, switch code using enumerations is more readable.
enum Signal {RED, YELLOW, GREEN}public static String getTrafficInstruct(Signal signal) { String instruct = "Signal light failure"; switch (signal) { case RED: instruct = "Red light stop"; break; case YELLOW: instruct = "Please pay attention to yellow light"; break; case GREEN: instruct = "Green light line"; break; default: break; } return instruct;}Organize enumeration
Enumerations of similar types can be organized through interfaces or classes.
However, it is generally organized by interface.
The reason is: the Java interface will automatically add public static modifier to the enum type when compiling; the Java class will automatically add static modifier to enum type when compiling. Have you seen the difference? That's right, that is, organize enum in the class. If you don't modify it to public , you can only access it in this package.
Example: Organize enums in interfaces
public interface Plant { enum Vegetable implements INumberEnum { POTATO(0, "potato"), TOMATO(0, "tomato"); Vegetable(int number, String description) { this.code = number; this.description = description; } private int code; private String description; @Override public int getCode() { return 0; } @Override public String getDescription() { return null; } } enum Fruit implements INumberEnum { APPLE(0, "Apple"), ORANGE(0, "Orange"), BANANA(0, "Banana"); Fruit(int number, String description) { this.code = number; this.description = description; } private int code; private String description; @Override public int getCode() { return 0; } @Override public String getDescription() { return null; } }}Example: Organize enums in a class
This example has the same effect as the previous example.
public class Plant2 { public enum Vegetable implements INumberEnum {...} // Omit the code public enum Fruit implements INumberEnum {...} // Omit the code}Strategy Enumeration
An enumeration of strategy is shown in Effective Java. This enumeration classifies enum constants by enumeration nested enumerations.
Although this approach is not as concise as the switch statement, it is safer and more flexible.
Example: Example of policy enumeration in EffectvieJava
enum PayrollDay { MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(PayType.WEEKEND), SUNDAY(PayType.WEEKEND); private final PayType payType; PayrollDay(PayType payType) { this.payType = payType; } double pay(double hoursWorked, double payRate) { return payType.pay(hoursWorked, payRate); } // Policy enum private enum PayType { WEEKDAY { double overtimePay(double hours, double payRate) { return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT) * payRate / 2; } }, WEEKEND { double overtimePay(double hours, double payRate) { return hours * payRate / 2; } }; private static final int HOURS_PER_SHIFT = 8; abstract double overtimePay(double hrs, double payRate); double pay(double hoursWorked, double payRate) { double basePay = hoursWorked * payRate; return basePay + overtimePay(hoursWorked, payRate); } }}test
System.out.println("Earnings for people who earn 100 an hourly wage on Friday for 8 hours: " + PayrollDay.FRIDAY.pay(8.0, 100)); System.out.println("Earnings for people who earn 100 an hourly wage on Saturday for 8 hours: " + PayrollDay.SATURDAY.pay(8.0, 100));EnumSet and EnumMap
Java provides two tool classes that are convenient for operating enum - EnumSet and EnumMap.
EnumSet is a high-performance Set implementation of enum types. It requires that the enum constants placed in it must belong to the same enum type.
EnumMap is a Map implementation tailored for enum types. Although using other Map implementations (such as HashMap) can also complete enum type instances to value mapping, using EnumMap is more efficient: it can only receive instances of the same enum type as key values, and because the number of enum type instances is relatively fixed and limited, EnumMap uses an array to store the values corresponding to the enum type. This makes EnumMap very efficient.
// Use of EnumSet System.out.println("EnumSet display");EnumSet<ErrorCodeEn> errSet = EnumSet.allOf(ErrorCodeEn.class); for (ErrorCodeEn e : errSet) { System.out.println(e.name() + " : " + e.ordinal());}// Use of EnumMap System.out.println("EnumMap display");EnumMap<StateMachine.Signal, String> errMap = new EnumMap(StateMachine.Signal.class);errMap.put(StateMachine.Signal.RED, "Red Light");errMap.put(StateMachine.Signal.YELLOW, "Yellow");errMap.put(StateMachine.Signal.GREEN, "Green Light");for (Iterator<Map.Entry<StateMachine.Signal, String>> iter = errMap.entrySet().iterator(); iter.hasNext();) { Map.Entry<StateMachine.Signal, String> entry = iter.next(); System.out.println(entry.getKey().name() + " : " + entry.getValue());}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.