2020.1.25 Java enum Comments

Java enum

What is an enumeration type

JDK5 introduces a new feature, you can create a keyword enum finite set of values ​​to be named as a new type, and these values ​​can be named as a regular component uses, which is an enumerated type.

一个枚举的简单例子

enum SeasonEnum {
    SPRING,SUMMER,FALL,WINTER;
}

Common methods of enumeration class

Enum 常用方法有以下几种:

  • name (): Returns the enum name when the instance declaration
  • ORDINAL (); returns an int, enum indicates instances in the order stated
  • the equals (); returns a Boolean value, equal enum instance Analyzing
  • the compareTo (); enum sequentially comparing the specific object instance
  • values ​​(); Returns enum instance array
  • valuesOf (String name) Gets the name of the enumeration constants defined in class

结合例子实现

package com.legend.enumdemo;

/**
 * 枚举测试类
 */
enum Shrubbery {
    GROUND, CRAWLING, HANGING
}


/**
 * @author legend
 */
public class EnumClassTest {
    public static void main(String[] args) {
        //values 返回enum实例的数组
        for (Shrubbery temp : Shrubbery.values()) {
            // name 返回实例enum声明的名字
            System.out.println(temp.name() + " ordinal is " + temp.ordinal() + " ,equal result is " +
                    Shrubbery.CRAWLING.equals(temp) + ",compare result is " + Shrubbery.CRAWLING.compareTo(temp));
        }
        //由名称获取枚举类中定义的常量值
        System.out.println(Shrubbery.valueOf("CRAWLING"));
    }
}

Enum class true colors

Enumerated types in the end what kind of it?

  • Create a simple enumeration
public enum Shrubbery {
    GROUND,CRAWLING, HANGING
}
  • Use javac to compile the above enumerated classes, available Shrubbery.class file.
javac Shrubbery.java
  • Then javap command, decompile get bytecode files. Such as: the following may be performed javap Shrubbery.class byte code file.
Compiled from "Shrubbery.java"
public final class enumtest.Shrubbery extends java.lang.Enum<enumtest.Shrubbery> {
  public static final enumtest.Shrubbery GROUND;
  public static final enumtest.Shrubbery CRAWLING;
  public static final enumtest.Shrubbery HANGING;
  public static enumtest.Shrubbery[] values();
  public static enumtest.Shrubbery valueOf(java.lang.String);
  static {};
}

From bytecode files can be found:

- Shrubbery 枚举变成了一个final修饰的类,也就是说,他不能被继承
- Shrubbery是java.lang.Enum的子类
- Shrubbery定义的枚举值都是 public static final 修饰的,即都是静态变量

Advantage enumeration class

What are the advantages enumeration class? It is why we choose to use the enumerated classes? Because it enhances code readability, maintainability, at the same time, it also has security.

Enum class can enhance the readability, maintainability

Suppose now that there is such a business scenario: After the order is complete, notify the buyer comment. It is easy to have the following code:

//订单已完成
if(3==orderStatus){
    //do something    
}

Obviously, this code appeared the magic number, if you did not write notes, who knows what state 3 indicates that the order does not only difficult to read, maintain, and very boring? If you use the enumeration class as follows:

public enum OrderStatusEnum {
    UNPAID(0, "未付款"),
    PAID(1, "已付款"),
    SEND(2, "已发货"),
    FINISH(3, "已完成"),
    ;

    private int index;

    private String desc;

    public int getIndex() {
        return index;
    }

    public String getDesc() {
        return desc;
    }

    OrderStatusEnum(int index, String desc) {
        this.index = index;
        this.desc = desc;
    }
}


//订单已完成
 if(OrderStatusEnum.FINISH.getIndex()==orderStatus){
  //do something
 }

Visible, enumeration class make this code more readable, it is better to maintain, plus behind the new order status, add one more direct enumeration state on it, some people think, public static final int this static const can also achieve this function ah

public class OrderStatus {
    //未付款
    public static final int UNPAID = 0;
    public static final int PAID = 1;
    public static final int SENDED = 2;
    public static final int FINISH = 3;
    
}

//订单已完成
if(OrderStatus.FINISH==orderStatus){
    //do something
}

Of course, to achieve static constants in this way, the readability is no problem
, however, the same variables defined int value, confusing, as you define PAID and SENDED state is 2, the compiler is not being given.

Therefore, enumeration class first advantage is readability, maintainability are good, it is recommended.

Enum class security

Apart from the readability, maintainability, and enumerated classes there is a huge advantage is security.

From an enumeration class bytecode analysis we know:

  • An enumeration class is final keyword modified, it can not be inherited
  • And its public static final variables are modified, are static constants

When a Java class for the first time is really used to when static resources are initialized, and the initialization process load Java classes are thread-safe.

Enumeration of common usage

enum constant organization

Before JDK5, the constants are defined such, define a class or interface, attribute types are public static final ..., then with enumeration, the constant can be organized into the enumerated classes, as follows:

enum SeasonEnum {
    SPRING,SUMMER,FALL,WINTER,;
}

enum switch interlocking with

Generally, switch-case can use only integer values, but have a natural order enumerate instances of integer values, and therefore, in the switch statement is enum can be used, as follows:

enum OrderStatusEnum {
   UNPAID, PAID, SEND, FINISH
}

package com.legend.enumdemo.advantage;

/**
 * enum-switch 相结合使用测试
 *
 * @author legend
 */
public class OrderStatusTest {
    public static void main(String[] args) {
        //改变订单状态
        changeByOrderStatus(OrderStatusEnum.FINISH);

    }

    /**
     * 改变订单状态
     *
     * @param orderStatusEnum
     */
    private static void changeByOrderStatus(OrderStatusEnum orderStatusEnum) {
        switch (orderStatusEnum) {
            case UNPAID:
                System.out.println("你下单了,赶紧付钱吧");
                break;
            case PAID:
                System.out.println("我已经付钱啦");
                break;
            case SEND:
                System.out.println("已发货");
                break;
            case FINISH:
                System.out.println("订单完成啦");
                break;
        }
    }
}

In the daily development, enum used in conjunction with the switch, make your code more readable

Add a new approach to the enumerated classes, such as the get method, ordinary methods, it is the daily work of the most commonly used enumeration wording:

public static OrderStatusEnum of(int index) {
    for (OrderStatusEnum temp : values()) {
        if (temp.getIndex() == index) {
            return temp;
        }
    }
    return null;
}

Enumeration implements the interface

All of the enumeration classes inherit so enumeration can not inherit from other classes with java.lang.Enum. But the enumeration interface can be achieved, as follows:

public interface Food {
    enum Coffee implements Food{
        BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO
    }

    enum Dessert implements Food{
        FRUIT, CAKE, GELATO
    }
}

The enumeration class comparison is == or equals?

package com.legend.enumdemo.equals;

/**
 * 枚举类比较
 *
 * @author legend
 */
public class EnumTest {

    public static void main(String[] args) {

        Shrubbery s1 = Shrubbery.CRAWLING;
        Shrubbery s2 = Shrubbery.GROUND;
        Shrubbery s3 = Shrubbery.CRAWLING;

        System.out.println("s1==s2,result: " + (s1 == s2));
        System.out.println("s1==s3,result: " + (s1 == s3));
        System.out.println("Shrubbery.CRAWLING.equals(s1),result: " + Shrubbery.CRAWLING.equals(s1));
        System.out.println("Shrubbery.CRAWLING.equals(s2),result: " + Shrubbery.CRAWLING.equals(s2));

    }
}

运行结果:

s1==s2,result: false
s1==s3,result: true
Shrubbery.CRAWLING.equals(s1),result: true
Shrubbery.CRAWLING.equals(s2),result: false

It can be found not work == or equals are possible. In fact, the US drama equals method is to use == comparison

public final boolean equals(Object other) {
    return this==other;
}

Single embodiment implemented enumeration

effective java mentioned, is the best mode embodiment of the single mode enumeration. Achieve Singleton pattern There are several ways to achieve the best way to enumerate Why?

Because a single embodiment has the following advantages enumerated achieved:

  • Example enumeration single simple wording
  • Enumeration solve thread safety issues
  • Enumeration solve the problem deserialization will destroy a single case

Example demo a single enumeration as follows:

package com.legend.enumdemo.singleton;

/**
 * 枚举实现的单例
 *
 * @author legend
 */
public class SingletonEnumTest {

    public static void main(String[] args) {
        SingletonEnum.INSTANCE.setName("legend@qichunlin");
        System.out.println(SingletonEnum.INSTANCE.getName());
    }


    public enum SingletonEnum {
        INSTANCE,
        ;

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

EnumSet and EnumMap

EnumSet

先来看看EnumSet的继承体系图

Obviously, EnumSet also implements the interface set, compared to the HashSet, it has the following advantages:

  • Consume less memory
  • More efficient, because it is a bit vector implementation.
  • Predictable traversal order (enum constant declaration order)
  • Refuse to add null

EnumSet is set to achieve high performance, it is required to store must be the same enumerated type. EnumSet common methods:

  • allof () to create a collection that contains the specified enum class EnumSet all enumeration values
  • range() 获取某个范围的枚举实例
  • of() 创建一个包括参数中所有枚举元素的EnumSet集合
  • complementOf() 初始枚举集合包括指定枚举集合的补集
package com.legend.enumdemo.enumset;

import java.util.EnumSet;

/**
 * EnumSet枚举
 *
 * @author legend
 */
public class EnumTest {

    public static void main(String[] args) {

        EnumSet<SeasonEnum> set1, set2, set3, set4;

        set1 = EnumSet.of(SeasonEnum.SPRING, SeasonEnum.FALL, SeasonEnum.WINTER);
        set2 = EnumSet.complementOf(set1);
        set3 = EnumSet.allOf(SeasonEnum.class);
        set4 = EnumSet.range(SeasonEnum.SUMMER, SeasonEnum.WINTER);

        System.out.println("Set 1: " + set1);
        System.out.println("Set 2: " + set2);
        System.out.println("Set 3: " + set3);
        System.out.println("Set 4: " + set4);

    }
}

运行结果:

Set 1: [SPRING, FALL, WINTER]
Set 2: [SUMMER]
Set 3: [SPRING, SUMMER, FALL, WINTER]
Set 4: [SUMMER, FALL, WINTER]

EnumMap

EnumMap的继承体系图如下:

显然,EnumMap也实现了Map接口,相比于HashMap,它有以下优点:

  • 消耗较少的内存
  • 效率更高
  • 可以预测的遍历顺序
  • 拒绝 null

EnumMap就是map的高性能实现。 它的常用方法跟HashMap是一致的,唯一约束是枚举相关。

看实例

package com.legend.enumdemo.enummap;

import java.util.EnumMap;
import java.util.Map;

/**
 * enumMap 实现
 */
public class EnumTest {
    public static void main(String[] args) {
        Map<SeasonEnum, String> map = new EnumMap<SeasonEnum, String>(SeasonEnum.class);
        map.put(SeasonEnum.SPRING, "春天");
        map.put(SeasonEnum.SUMMER, "夏天");
        map.put(SeasonEnum.FALL, "秋天");
        map.put(SeasonEnum.WINTER, "冬天");

        System.out.println(map);
        System.out.println(map.get(SeasonEnum.SPRING));
    }
}

运行结果:

{SPRING=春天, SUMMER=夏天, FALL=秋天, WINTER=冬天}
春天

Guess you like

Origin www.cnblogs.com/qichunlin/p/12233043.html