enum enumeration usage

JDK1.5 introduces a new type - enumeration. In Java, although it considered a "small" feature, I gave my development has brought "great" convenience.

Big Brother I add my own understanding, to help you understand it.

Use a: constant

Before JDK1.5, we define constants are: public static final ..... Well now, with the enumeration constants it can be related to a group enumeration type, the enumeration and provides more than constant method. 

Java code 

public enum Color {  
  RED, GREEN, BLANK, YELLOW  
} 

Usage of Two: switch

Before JDK1.6 switch statement only supports int, char, enum type, enum, make our code more readable. 

Java code 

enum Signal {  
    GREEN, YELLOW, RED  
}  
public class TrafficLight {  
    Signal color = Signal.RED;  
    public void change() {  
        switch (color) {  
        case RED:  
            color = Signal.GREEN;  
            break;  
        case YELLOW:  
            color = Signal.RED;  
            break;  
        case GREEN:  
            color = Signal.YELLOW;  
            break;  
        }  
    }  
}  

Use three: add a new method to enumeration

If you plan to customize your own way, then finally add a semicolon to be serialized in the enum instance. Requirements must be defined and Java enum instance. 

Java code 

public enum Color {  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
    // 普通方法  
    public static String getName(int index) {  
        for (Color c : Color.values()) {  
            if (c.getIndex() == index) {  
                return c.name;  
            }  
        }  
        return null;  
    }  
    // get set 方法  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getIndex() {  
        return index;  
    }  
    public void setIndex(int index) {  
        this.index = index;  
    }  
}  

Usage four: covering enumeration method

Here's an example of the method covered toString (). 

Java code 

public enum Color {  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
    //覆盖方法  
    @Override  
    public String toString() {  
        return this.index+"_"+this.name;  
    }  
}  

Usage five: implement an interface

All of the enumeration classes inherit from java.lang.Enum. Because Java does not support multiple inheritance, so enumerable object can not inherit from other classes. 

Java code 

public interface Behaviour {  
    void print();  
    String getInfo();  
}  
public enum Color implements Behaviour{  
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);  
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
//接口方法  
    @Override  
    public String getInfo() {  
        return this.name;  
    }  
    //接口方法  
    @Override  
    public void print() {  
        System.out.println(this.index+":"+this.name);  
    }  
}  


Usage six: Use Interface organization enumeration


 Java code 

public interface Food {  
    enum Coffee implements Food{  
        BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO  
    }  
    enum Dessert implements Food{  
        FRUIT, CAKE, GELATO  
    }  
}  
    /**
     * 测试继承接口的枚举的使用(by 大师兄 or 大湿胸。)
     */
    private static void testImplementsInterface() {
        for (Food.DessertEnum dessertEnum : Food.DessertEnum.values()) {
            System.out.print(dessertEnum + "  ");
        }
        System.out.println();
        //我这地方这么写,是因为我在自己测试的时候,把这个coffee单独到一个文件去实现那个food接口,而不是在那个接口的内部。
        for (CoffeeEnum coffee : CoffeeEnum.values()) {
            System.out.print(coffee + "  ");
        }
        System.out.println();
        //搞个实现接口,来组织枚举,简单讲,就是分类吧。如果大量使用枚举的话,这么干,在写代码的时候,就很方便调用啦。
        //还有就是个“多态”的功能吧,
        Food food = Food.DessertEnum.CAKE;
        System.out.println(food);
        food = CoffeeEnum.BLACK_COFFEE;
        System.out.println(food);
    }


operation result

Usage seven: Use an enumeration on the set

java.util.EnumSet and java.util.EnumMap are two enumerations. EnumSet ensure the collection of elements is not repeated; EnumMap enum type is the key, but may be any type of value. About the use of the two sets will not go into here, you can refer to the JDK documentation.

About Enumeration principles and implementation details, please refer to:

Reference: "ThinkingInJava" Fourth Edition

http://softbeta.iteye.com/blog/1185573

 

My article, because it is reproduced, it may be basically unchanged, result in someone stepped on his foot. That does not meet my big brother character. Now I understand their use to sort out.

 

But also because because it was just starting to learn it. The usually we think we know everything just know a bit about, after all, or think we know, in fact, gone do not know what it is.
Out of learning, not used to look at the code how can do it?
Here is my own test code.

package com.lxk.enumTest;
 
/**
 * Java枚举用法测试
 * <p>
 * Created by lxk on 2016/12/15
 */
public class EnumTest {
    public static void main(String[] args) {
        forEnum();
        useEnumInJava();
    }
 
    /**
     * 循环枚举,输出ordinal属性;若枚举有内部属性,则也输出。(说的就是我定义的TYPE类型的枚举的typeName属性)
     */
    private static void forEnum() {
        for (SimpleEnum simpleEnum : SimpleEnum.values()) {
            System.out.println(simpleEnum + "  ordinal  " + simpleEnum.ordinal());
        }
        System.out.println("------------------");
        for (TYPE type : TYPE.values()) {
            System.out.println("type = " + type + "    type.name = " + type.name() + "   typeName = " + type.getTypeName() + "   ordinal = " + type.ordinal());
        }
    }
 
    /**
     * 在Java代码使用枚举
     */
    private static void useEnumInJava() {
        String typeName = "f5";
        TYPE type = TYPE.fromTypeName(typeName);
        if (TYPE.BALANCE.equals(type)) {
            System.out.println("根据字符串获得的枚举类型实例跟枚举常量一致");
        } else {
            System.out.println("大师兄代码错误");
        }
 
    }
 
    /**
     * 季节枚举(不带参数的枚举常量)这个是最简单的枚举使用实例
     * Ordinal 属性,对应的就是排列顺序,从0开始。
     */
    private enum SimpleEnum {
        SPRING,
        SUMMER,
        AUTUMN,
        WINTER
    }
 
 
    /**
     * 常用类型(带参数的枚举常量,这个只是在书上不常见,实际使用还是很多的,看懂这个,使用就不是问题啦。)
     */
    private enum TYPE {
        FIREWALL("firewall"),
        SECRET("secretMac"),
        BALANCE("f5");
 
        private String typeName;
 
        TYPE(String typeName) {
            this.typeName = typeName;
        }
 
        /**
         * 根据类型的名称,返回类型的枚举实例。
         *
         * @param typeName 类型名称
         */
        public static TYPE fromTypeName(String typeName) {
            for (TYPE type : TYPE.values()) {
                if (type.getTypeName().equals(typeName)) {
                    return type;
                }
            }
            return null;
        }
 
        public String getTypeName() {
            return this.typeName;
        }
    }
}


Then the test results chart:

A simple example, we basically have used, basically I do not understand the second example. It can be seen in the second example, followed by a parameter, in fact, can be understood.

enum keyword, it can be understood as almost like class, which is also a separate class. Can be seen, there are properties of the above example, the method has a structure, there getters, the setter may also have, but generally are configured to pass parameters. There are other custom methods. So in front of these things, separated by commas, and finally end with a semicolon, this part is called, an instance of this enumeration. It can also be understood as, class new instance of the object out. This time enough to understand. Only, class, new object, you can own any new, few would want a few, and this enum keyword, he would not, he's instance of an object, which can only be reflected in the enum. In other words, examples of his correspondence is limited. This is an enumeration of benefits, and limits the scope of certain things, give chestnuts: Throughout the year, there can be only seasons, if you string representation, then it went to the sea, however, to use enumerated type, then you have all the options, all came, then the property this season, the corresponding values ​​are listed in the enum inside braces, you can only pick inside. You can not have the other.

My example above is based on typeName, you can pick from the example of those inside to enumerate instances only one type TYPE --TYPE.BALANCE. Note Method

TYPE type = TYPE.fromTypeName (typeName);
return type is an enumerated type of the TYPE this method.
This time like to understand, this is how the enumeration work in the bar

Then add:

Examples of the above enumerated type with parameters which are actually three properties, in addition to the typeName my custom, there are two system comes. See FIG source below:

After seeing this, I do not know if you can understand the words of the instructions in the following picture: The following pictures illustrate the main use of enumeration, norms and standards. Hope can be used in the actual development time

Finally, add this:

Maybe you know about it, but maybe you do not know anything about it? I really do not know, only after the test! ! !

Comparison between the value of the enumerated type objects, == is used directly to compare values, whether equal, not necessary to use the equals method yo.

In particular, please refer to the following links:

java enum class comparison is == or equals?

2017.11.07 update

Some old iron, how to write this switch case, I will look at the following long-winded.

   

private static void testSwitchCase() {
        String typeName = "f5";
        //这几行注释呢,你可以试着三选一,测试一下效果。
        //String typeName = "firewall";
        //String typeName = "secretMac";
        TypeEnum typeEnum = TypeEnum.fromTypeName(typeName);
        if (typeEnum == null) {
            return;
        }
        switch (typeEnum) {
            case FIREWALL:
                System.out.println("枚举名称(即默认自带的属性 name 的值)是:" + typeEnum.name());
                System.out.println("排序值(默认自带的属性 ordinal 的值)是:" + typeEnum.ordinal());
                System.out.println("枚举的自定义属性 typeName 的值是:" + typeEnum.getTypeName());
                break;
            case SECRET:
                System.out.println("枚举名称(即默认自带的属性 name 的值)是:" + typeEnum.name());
                System.out.println("排序值(默认自带的属性 ordinal 的值)是:" + typeEnum.ordinal());
                System.out.println("枚举的自定义属性 typeName 的值是:" + typeEnum.getTypeName());
                break;
            case BALANCE:
                System.out.println("枚举名称(即默认自带的属性 name 的值)是:" + typeEnum.name());
                System.out.println("排序值(默认自带的属性 ordinal 的值)是:" + typeEnum.ordinal());
                System.out.println("枚举的自定义属性 typeName 的值是:" + typeEnum.getTypeName());
                break;
            default:
                System.out.println("default");
        }
    }


Then, is shot run of results.

Old iron who, after reading this enumeration, you have to understand a concept, that is, this enumeration, he is a target, just as you define the Student class, Person class, so some of the classes.

Have such a concept. As long as a class, he can have a constructor can have attributes, there are ways.

Then, you see, this place has two default attributes, one name, one is ordinal, these two attributes like name and age you define the Student class and as the Person class,

But, this is the system comes with two properties, you do not have to define it.

You can also give the enumerated classes, that is to enumerate your own statement, seek to raise property.

I have the above code examples inside that TypeEnum the enumeration, is so dry, it's simple to add a custom attribute typeName,

Although he has his own name, then tentatively called me this custom attribute called aliases it.

I can see that I am an example of which is through the construction method to write the initial value of this property to my custom.

Moreover, this construction method is not, nor is running public, do not believe you can try.

Also, you can not attribute the system comes with the name, in the constructor function assignment, there is no why.
 

Published 13 original articles · won praise 1 · views 7816

Guess you like

Origin blog.csdn.net/weixin_40482816/article/details/88862083