knowledge

concept

The full name of enum, enumeration, is a new feature introduced in JDK 1.5.

In Java, a type decorated with the enum keyword is an enumerated type. The form is as follows:

enum Color { RED, GREEN, BLUE }Copy the code

If the enumeration does not add any methods, the enumeration value defaults to an ordered value starting at 0. Take the Color enumeration type for example, whose enumeration constants are RED: 0, GREEN: 1, and BLUE: 2.

Benefits of enumerations: Constants can be organized and managed uniformly.

Typical application scenarios of enumeration include error codes and state machines.

The nature of enumerated types

Although enum may seem like a new data type, it is, in fact, a restricted class with its own methods.

When you create an enum, the compiler generates an associated class for you that inherits from java.lang.enum.

Java. Lang. Enum class declaration

public abstract class Enum<E extends Enum<E>>        implements Comparable<E>, Serializable { ... }Copy the code

Method of enumeration

In enum, some basic methods are provided:

Values () : Returns an array of instances of enum, and the elements in that array remain in the exact order in which they were declared in the enum.

Name () : Returns the instance name.

Ordinal () : Returns the order in which the instance was declared, starting from 0.

GetDeclaringClass () : Returns the enum type to which the instance belongs.

Equals () : Checks whether they are the same object.

Enum instances can be compared using ==.

In addition, java.lang.enum implements the Comparable and Serializable interfaces, so it also provides the compareTo() method. Everything you need to know about Java serialization is recommended.

Example: Show the basic method of 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.name()); System.out.println("green getDeclaringClass(): " + 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); }}Copy the code

The output

=========== Print all Color ===========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: falsegreen equals 1: falsegreen == Color.BLUE: falseCopy the code

Features of enumeration

The nature of enumerations boils down to one sentence:

Except that you can’t inherit, you can basically think of enum as a regular class.

But this sentence needs to be broken down to understand. Let’s break it down.

Enumerations can add methods

As mentioned in the Concepts section, enumeration values default to ordered values starting at 0. The problem then is how to assign values to enumeration displays.

Java does not allow the use of = to assign values to enumeration constants

If you’re familiar with C/C++, you’ll naturally think of the assignment symbol =. In C/C++, we can assign values to enum constants using the assignment symbol =. Unfortunately, Java syntax does not allow the use of the assignment symbol = to assign values to enumerated constants.

Example: enumeration declarations in C/C++

typedef enum{    ONE = 1,    TWO,    THREE = 3,    TEN = 10} Number;Copy the code

Enumerations can add normal methods, static methods, abstract methods, and constructors

While Java cannot assign an instance directly, it has a better solution: add methods to enums to implement explicit assignment indirectly.

When you create an enum, you can add multiple methods to it, and you can even add constructors to it.

Note one detail: if you define a method for an enum, you must add a semicolon to the end of the last instance of the enum. Also, in enUms, instances must be defined first, and fields or methods cannot be defined before instances. Otherwise, the compiler will report an error.

Example: How to define normal methods, static methods, abstract methods, constructors in enumeration

Public enum ErrorCode {OK(0) {public String getDescription() {return "success "; }, ERROR_A(100) {public String getDescription() {return "error A"; }, ERROR_B(200) {public String getDescription() {return "error B"; }}; private int code; private ErrorCode(int number) { this.code = number; } public int getCode() { return code; } public abstract String getDescription(); public static void main(String args[]) { for (ErrorCode s : ErrorCode.values()) { System.out.println("code: " + s.getCode() + ", description: " + s.getDescription()); }}}Copy the code

Note: The above example is not desirable and is merely intended to show that enumerations support defining various methods. Here is a simplified example

Example: an error code enumeration type definition

The result in this example is the same as that in the preceding example.

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[]) { for (ErrorCodeEn s : ErrorCodeEn.values()) { System.out.println("code: " + s.getCode() + ", description: " + s.getDescription()); }}}Copy the code

Enumerations can implement interfaces

enumInterfaces can be implemented just like normal classes.

Also implementing the error code enumeration class in the previous section, you can constrain its methods by implementing an interface.

public interface INumberEnum { int getCode(); String getDescription(); }public enum ErrorCodeEn2 implements INumberEnum {OK(0, "successful "), 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; }}Copy the code

Enumerations cannot be inherited

An enum cannot inherit from another class, nor, of course, from another enum.

Because enums actually inherit from the java.lang. enum class, and Java does not support multiple inheritance, enums cannot inherit from other classes, and certainly cannot inherit from another enum. In addition, follow the wechat public account: Java technology stack, in the background reply: Java, you can get the N most complete Java tutorial I organized, are dry goods.

Application scenarios of enumeration

Group constants

Before JDK1.5, constants in Java were defined as public static final TYPE a; It looks like this. With enumerations, you can organize constants that are related to each other, making your code more readable, safer, and using the methods provided by enumerations.

Enumerates the format of the declaration

Note: If no method is defined in the enumeration, you can also add a comma, semicolon, or nothing after the last instance.

The following three declarations are equivalent:

enum Color { RED, GREEN, BLUE }enum Color { RED, GREEN, BLUE, }enum Color { RED, GREEN, BLUE; }Copy the code

The switch state machine

We often use switch statements to write state machines. After JDK7, the switch supports int, CHAR, String, and enum parameters. 6 Data Types Supported by Switch Case Switch code using enumerations is more readable than these types of parameters.

Enum Signal {RED, YELLOW, GREEN}public static String getTrafficInstruct(Signal Signal) {String instruct = "traffic instruct "; Switch (signal) {case RED: instruct = "RED light stop "; break; Case YELLOW: instruct = "YELLOW light please note "; break; Case GREEN: instruct = "go GREEN "; break; default: break; } return instruct; }Copy the code

Organize the enumeration

Enumerations of similar types can be organized through interfaces or classes.

But it is generally organized in an interface manner.

The reason is that Java interfaces automatically add the public static modifier to enum types when compiled. Java classes automatically add the static modifier to enum types when compiled. See the difference? That’s right, that is, organize the enum in the class, and if you don’t decorate it with public, then it can only be accessed in this package.

For example, organize the enum in the interface

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; }}}Copy the code

Example: Organize an enum in a class

This example has the same effect as the previous example.

public class Plant2 { public enum Vegetable implements INumberEnum {... } public enum Fruit implements INumberEnum {... }}Copy the code

Strategy enumeration

EffectiveJava shows an enumeration of policies. This enumeration classifies enumeration constants by enumeration nested enumerations.

This approach is not as compact as the switch statement, but it is more secure and 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); } 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); }}}Copy the code

test

System.out.println(" payrollday.friday.pay (8.0, 100)); System.out.println(" payrollday.saturday.pay (8.0, 100));Copy the code

Enumsets and EnumMap

Java provides two utility classes for manipulating enUms, EnumSet and EnumMap.

EnumSet is a high-performance Set implementation of enumeration types. It requires that the enumeration constants put into it be of the same enumeration type. EnumMap is a Map implementation tailored specifically for enumeration types. While other Map implementations (such as HashMap) can do enumeration type instance-to-value mapping, using EnumMap is more efficient: It can only accept instances of the same enumeration type as key values, and because the number of instances of enumeration types is relatively fixed and limited, EnumMap uses arrays to hold values corresponding to enumeration types. This makes EnumMap very efficient.

System. The out. Println (" enumsets show "); EnumSet<ErrorCodeEn> errSet = EnumSet.allOf(ErrorCodeEn.class); for (ErrorCodeEn e : errSet) { System.out.println(e.name() + " : " + e.ordinal()); } System. Out. Println (" EnumMap show "); EnumMap<StateMachine.Signal, String> errMap = new EnumMap(StateMachine.Signal.class); Errmap. put(Statemachine.signal. RED, "RED "); ErrMap. Put (the StateMachine. Signal. YELLOW, "YELLOW"); ErrMap. Put (the StateMachine. Signal. GREEN, "GREEN"); 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()); }Copy the code

Source: www.cnblogs.com/jingmoxukong/p/6098351.html

– END –
Recommended reading:


12306’s architecture is too “awesome X”!
Spring Cloud updates the latest Greenwich release

Spring Boot 2.2.1 was released, a bit of a pothole
Head! RabbitMQ and Kafka?
Share a new Java Architect learning material for 2019
Java technology stack
Java

Click “Read the article” and stack length to learn more ~