20190925 On Java8 Chapter XXII enumeration

Chapter XXII enumeration

The basic characteristics of the enum

Created enum, the compiler will generate a class relevant for you, this class inherits from Java.lang.Enum.

valueOf()It is Enumdefined staticmethod, which returns the corresponding name from the given enumexample, if the given instance name does not exist, an exception is thrown.

The static type for introducing enum

Use static importcan be enumidentifiers instance into the current namespace, which eliminates the need enumto modify the type of enuminstance.

Add Method

In addition to an enum can not inherit from outside, we basically can enum as a regular class. That we can add methods to the enum. enum can even main()approach.

We can only create enum instance using its constructor inside the enum definition. Once the end of the enum definition, the compiler will not allow us to re-use its constructor to create any instances of.

The method of covering the enum

Covering toSring()method, it provides us with another way to generate different information string descriptor enumerate instances.

values Mystery method

Enum class created by the compiler are inherited from the Enumclass, but did not Enum class values()method. values()It is added by the compiler staticmethods. The compiler also to add a valueOf()method. Enum The valueOf()method requires two parameters, and this new method takes a single argument.

Since the values()method is inserted by the compiler to the static method enum definition, so, if you will enum instance upcast Enum, then the values()method will not be visited. However, there is a Class in the getEnumConstants()method, so even if there is no Enum interface values()method, we can still get through all instances enum Class object.

enum Search {
    HITHER, YON
}

public class UpcastEnum {
    public static void main(String[] args) {
        Search[] vals = Search.values();
        Enum e = Search.HITHER; // Upcast
        // e.values(); // No values() in Enum
        for (Enum en : e.getClass().getEnumConstants())
            System.out.println(en);
    }
}

Achieve rather than inheritance

All enum inherit from Java.lang.Enumclass. Because Java does not support multiple inheritance, so your enum can not inherit from other classes, however, when we create a new enum, may implement one or more interfaces simultaneously.

Use Interface organization enumeration

Within an interface, create an implementation of an enumeration of the interface, in order to group elements, can achieve the purpose of the enumeration element classification organization.

public interface Food {
    enum Appetizer implements Food {
        SALAD, SOUP, SPRING_ROLLS;
    }

    enum MainCourse implements Food {
        LASAGNE, BURRITO, PAD_THAI, LENTILS, HUMMOUS, VINDALOO;
    }

    enum Dessert implements Food {
        TIRAMISU, GELATO, BLACK_FOREST_CAKE, FRUIT, CREME_CARAMEL;
    }

    enum Coffee implements Food {
        BLACK_COFFEE, DECAF_COFFEE, ESPRESSO, LATTE, CAPPUCCINO, TEA, HERB_TEA;
    }
}

Use EnumSetalternative Flags

ava SE5 introduced EnumSet, in order to create an alternative to pass enum, instead of based on the traditional "flag" int's. EnumSet design fully into account the speed factor.

use EnumMap

EnumMapIt is a special kind of the Map, which requires wherein the key (key) must be from a enum, due to limitations enum itself, so EnumMap be implemented within the array. EnumMap very quickly.

Constant particular method

Java's enum has a very interesting feature that allows programmers to write methods to enum instance, giving their different behavior for each enum instance. To achieve a constant related, enum you need to define one or more abstract method, then implement the abstract method for each instance enum.

public enum OverrideConstantSpecific {
    NUT, BOLT, WASHER {
        @Override
        void f() {
            System.out.println("Overridden method");
        }
    };
    void f() {
        System.out.println("default behavior");
    }

    public static void main(String[] args) {
        for (OverrideConstantSpecific ocs : values()) {
            System.out.print(ocs + ": ");
            ocs.f();
        }
    }
}

Use of the chain of responsibility enum

In the duty chain (Chain of Responsibility) design mode, the programmer in a variety of different ways to solve a problem, and then link them together. When a request comes in, which traverse the chain until the chain a solution is able to handle the request.

State machine using enum

Enumerated type is well suited for creating state machines. A state machine having a finite number of specific state, it is usually based on the input, the state transition from one state to the next, but there may also be an instantaneous state (transient states), once the end of the task execution, the state machine will leave a transient state immediately .

Multi-channel distribution

Java supports only single-channel distribution. In other words, if the operation to be performed include more than one type of unknown objects, Java's dynamic binding mechanism to deal with only one type.

Guess you like

Origin www.cnblogs.com/huangwenjie/p/11588366.html
Recommended