Today’s sharing started, please give us more advice ~

A Java enumeration is a type that is qualified by the enum keyword. If an enumeration does not add any methods, the enumeration defaults to an ordered value starting at 0. For example, enum Color{RED, GREEN, BLUE}; Organize constants for unified management. Application scenarios include error codes and state machines. Enumeration is essentially a subclass of java.lang.Enum.

1. Basic Concepts

Enumeration is a new feature introduced in Java1.5 that defines enum classes through the keyword enum. An enumerated class is a special class that can use constructors, define member variables and methods, and implement one or more interfaces, just like a normal class, but an enumerated class cannot inherit from another class.

The advantages and disadvantages of enumeration

1, the advantages of

Effctive Java recommends enumerations instead of all constant codes for the following reasons:

(1) Type check and validity check

(2) Enumerations, as a class, can have their own attributes (usually constants, I’ve never seen that not) and their own methods (otherwise they can only be written in switch, which is a violation of principle).

(3) Compared with constant, you can directly know all possible return values without looking at the document and source code, convenient coding.

However, the problem here is the first point, in fact, distributed environment (1) is not inevitable. If an interface return value is allowed to have undefined content in a business process, then it should not be thrown in deserialization, so you don’t have to stick to (1). At the same time, from points (2) and (3), the effect of limiting the scope of enumeration is significant. Rewriting enumerations with their own attributes and methods to match code with other methods increases the amount of code required and the code rot greatly.

2 and disadvantages

(1) Because Java supports single inheritance, enumeration types cannot inherit from other classes;

(2) use enumerated as the return value may cause the problem is in fact we all know that the client and the server version do not agree, will cause the deserialization is unusual, so “alibaba JAVA development manual” for the problem of processing method is adopted to avoid abnormal, so define enumeration for the return value is prohibited.

Solve ifelse

For business development, the complexity of business logic is inevitable. With the development of business, the requirements will only become more and more complex. In order to take into account various situations, there will inevitably be many IF-else in the code.

If there is too much if-else in the code, it will greatly affect the readability and maintainability, and the code will look low.

Enumerations solve this problem;

Enumeration and switch is a relatively simple topic. When using switch for conditional judgment, conditional parameters can only be integers and characters. Enumerations are indeed supported by the Switch, which has supported strings since Java 1.7. Here’s a quick look at the use of switch and enumerated types

Common methods of enumeration

1. Enumerate classes

2. Add attributes to enumeration class variables

3. Test classes

Public static void main(String[] args) {//1, ordinal(), system.out.println (” + weekday.monday. //1 /* * 2, valueOf() * public static <T extends Enum> T valueOf(Class enumType, String name) Returns an object of a constant class. * name — This is the constant name to return. * return: This method returns an enumeration constant of an enumeration type with the specified name. * If you pass a string that does not exist, an exception will be thrown. * */ Week week = Enum.valueOf(Week.class,Week.MONDAY.name().toString()); Week week1 = Week.valueOf(Week.class,Week.MONDAY.name()); System.out.println(“Enum.valueOf,”+week); //MONDAY System.out.println(“Week.valueOf,”+week1); //3, values() system.out.println (” week.values (),”+ weekday.values ()); / / returns an array of Weekday, [Ljavase. Enumeration. Weekday; @2a84aee7 //4, compare by compareTo method, actually compare internally by ordinal() value System.out.println(“Weekday.MONDAY.compareTo(Weekday.TUESDAY),”+Weekday.MONDAY.compareTo(Weekday.TUESDAY)); //false

// Get a reference to the Class object of the enumeration. > declaringClass = Weekday.MONDAY.getDeclaringClass(); System.out.println(" Get the Class object reference for this enumeration object,"+declaringClass); / / javase. Enumeration. Weekday / / 6, through getEnumConstants () get all the elements of the enumerated type, if the Class object is not enumerated types, it returns null. Object[] enumConstants = declaringClass.getEnumConstants(); // Enumerate the number of classes, weekday.values ().length) for (int I = 0; i < Weekday.values().length; i++) { System.out.println("getEnumConstants,"+enumConstants[i]); SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY} //7. Check whether it is an enumeration type System.out.println("declaringClass.isEnum(),"+declaringClass.isEnum()); System.out.println(" number,"+ week.monday.getid ()+", meaning,"+ week.monday.getMeaning ()); } `Copy the code

4. Move up

What it means remains to be studied.

5, part of the method source code introduction

(1) the valueof

CompareTo (2)

Define abstract methods in an enumeration class

Define abstract methods

2. Test classes

3. Console output

Six, implementation interface

1, interfaces,

2. Implementation interface

3. Test classes

// implement the interface and call the methods in the interface

MONDAY.StudyDataStrucure();

4. Console output

Enumeration to realize singleton

Enum Singleton is mentioned in Effective Java, which is highly recommended by the author because of its complete functions, simple usage, free serialization mechanism, and absolute protection against multiple instantiations in the face of complex serialization or reflection attacks.

Eight, EnumMap

1. Code examples analyze EnumMap and HashMap

Take studying different Java projects from January to June as an example.

2. Console output

3. Result analysis

A HashMap contrast EnumMap

The output of HashMap and EnumMap is the same as that of EnumMap, which proves that enumerations can be used. However, as EnumMap is a collection of enumerations, there is no reason to use HashMap. After all, EnumMap requires that its Key must be of Enum type.

Because the number of instances of enumerations is relatively fixed and limited, EnumMap uses arrays to hold values corresponding to enumerations. After all, arrays are contiguous memory space, which is efficient because of program locality.

EnumMap needs to pass a type of information, a Class object. This parameter initializes the internal data structure based on the type information, or it can be initialized with a Map collection.

The key value cannot be null.

4. Simple source code analysis

(1) EnumMap inherits AbstractMap class, so EnumMap has the usage methods of general map.

(2) Because the key value is basically fixed, the underlying array implementation, higher efficiency

(3) Obtain the key array method

(4) the put ()

(5) the get ()

(6) remove ()

(7) either containsKey ()

Key is not allowed to be null, value can be null. Each key has a corresponding index. The key array and value array can be accessed and manipulated by the index. So it’s more efficient than HashMap.

Summary:

Except that enumerations cannot be inherited, enums are basically considered a normal class. Java does not allow the use of assignment to enum constants. Enums can display assignment through methods. Enumerations can implement interfaces because enums actually inherit from the java.lang. enum class, and Java does not support multiple inheritance, so enums cannot inherit from other classes, and certainly cannot inherit from another enum.

Today’s share has ended, please forgive and give advice!