Detailed java enumeration

Introduction

Enumeration (enum) type is a new feature of java5, is a new type. This is how it is introduced in java programming thinking: the keyword enum can create a new type from a finite set of named values.
Simply put, enumerations can be conveniently used to define a set of constants. The constants defined before jdk1.5 are:

public class Color{
    public static final RED = 0;
    public static final GREEN = 1;
    public static final BLANK = 2;
    public static final YELLOW = 3;
}

And with enumeration, you can do this:

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

When you create an enum, the compiler will generate a related class for you, which inherits from java.lang.Enum. So enums cannot be inherited.

The following code shows some of the methods provided by Enum

package test;


enum Shrubbery{
    GROUND,
    CRAWLING,
    HANGING
}

public class EnumClass {

    public static void main(String[] args) {
        for (Shrubbery s : Shrubbery.values()){
            System.out.println(s + "ordinal:" + s.ordinal());
            System.out.println("compareTo Shrubbery.CRAWLING:" + s.compareTo(Shrubbery.CRAWLING));
            System.out.println("equals():" + s.equals(Shrubbery.CRAWLING));
            System.out.println("==:" + (s == Shrubbery.CRAWLING));
            System.out.println(s.getDeclaringClass());
            System.out.println(s.name());
            System.out.println("-------------------------------");
        }

        for (String s : "HANGING CRAWLING GROUND".split(" ")){
            Shrubbery shrub = Enum.valueOf(Shrubbery.class, s);
            System.out.println(shrub);
        }
    }
}
//输出:
GROUNDordinal:0
compareTo Shrubbery.CRAWLING:-1
equals():false
==:false
class test.Shrubbery
GROUND
-------------------------------
CRAWLINGordinal:1
compareTo Shrubbery.CRAWLING:0
equals():true
==:true
class test.Shrubbery
CRAWLING
-------------------------------
HANGINGordinal:2
compareTo Shrubbery.CRAWLING:1
equals():false
==:false
class test.Shrubbery
HANGING
-------------------------------
HANGING
CRAWLING
GROUND

The ordinal() method returns an int, which is the order in which each enum instance was declared, starting at 0. You can use == to compare enum instances, and the compiler will automatically provide you with equals() and hashCode() methods. The Enum class implements the Comparable interface, so it has a compareTo() method. getDirclaringClass() method, we can know the enum class to which it belongs. The name() method returns the name of the enum instance when it is declared, and has the same effect as the toString() method. valueOf is a static method defined in Enum. It returns the corresponding enum instance according to the given name. If there is no instance with the given name, an exception will be thrown.

use

There are seven common uses of enums

1. Constants

Just as we gave a simple example at the beginning, a set of constants can be defined.

2.switch

The switch statement before JDK1.6 only supports int, char, and enum types. Using enumeration can make our code more readable.

enum Color{
    GREEN,
    BLUE,
    YELLOW
}

public class ColorClass {

    public static void main(String[] args) {
        Color color = Color.GREEN;
        switch (color){
            case BLUE:
                System.out.println("color is blue");
                break;
            case GREEN:
                System.out.println("color is green");
                break;
            case YELLOW:
                System.out.println("color is yellow");
                break;
        }
    }
}

One thing to note, however, is that the switch statement in jdk1.7 can support parameters of type String. In fact, this new feature is implemented at the compiler level. At the level of the Java virtual machine and byte code, only types compatible with integer types are supported in switch statements.

3. Add a new method to the enumeration
public enum OzWitch {

    WEST("west"),
    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    private String description;

    private OzWitch(String description){
        this.description = description;
    }

    public String getDescription(){
        return description;
    }

    public static void main(String[] args) {
        for (OzWitch witch : OzWitch.values())
            System.out.println(witch + ":" + witch.getDescription());
    }
}

We can add methods to the enum, including the main() method. It should be noted that if you plan to define your own method, you must add a semicolon at the end of the enum instance sequence. At the same time, java requires that the enum instance must be defined first, otherwise an error will be reported.

4. Override the enum method

An enum can override the toString() method.

enum Color{
    GREEN,
    BLUE,
    YELLOW;

    @Override
    public String toString() {
        String id = name();
        String lower = id.substring(1).toLowerCase();
        return id.charAt(0) + lower;
    }
}

public class ColorClass {

    public static void main(String[] args) {
        for (Color c : Color.values()){
            System.out.println(c);
        }
    }
}
5. Implement the interface
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);  
    }  
}  

All enums inherit from the java.lang.Enum class. Since Java does not support multiple inheritance, enum objects can no longer inherit from other classes.

6. Use interfaces to organize enumerations

Because enums cannot inherit but we want to group the elements of an enum by using accumulation. At this time, we can create an enumeration that implements the interface within an interface, so as to group the elements, which can achieve the purpose of classifying and organizing the enumeration elements.

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, CAPUCCINO, TEA, HERB_TEA;
        }
    }
7. EnumSet and EnumMap

java.util.EnumSet and java.util.EnumMap are two enumeration sets. EnumSet ensures that the elements in the collection are not repeated; the key in EnumMap is of the enum type, and the value can be of any type. The use of these two sets will not be repeated here, you can refer to the JDK documentation.

Other features

An interesting feature of java's enums, which allows programmers to write methods for enum instances, is that each enum instance has its own different behavior.

enum Color{
    GREEN{
        public String getInfo(){
            return "color is green";
        }
    },
    BLUE{
        public String getInfo(){
            return "color is blue";
        }
    },
    YELLOW{
        public String getInfo(){
            return "color is blue";
        }
    };

    abstract public String getInfo();
}

public class ColorClass {

    public static void main(String[] args) {
        for (Color c : Color.values()){
            System.out.println(c.getInfo());
        }
    }
}

Reference:
"java programming ideas"
http://softbeta.iteye.com/blog/1185573

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325526498&siteId=291194637