Java enumeration type enum-depth understanding of

1. What is an enumeration

Enumeration is a data type, with a collection of some of the features, it can store multiple elements, but with limited storage and fixed objects, enumeration is also a relatively common usage scenarios, such as we need to express gender (male and female), color (red , yellow, blue), week (Monday, Tuesday ... Sunday), seasons (spring, summer, autumn, winter), geographic location (east, west, south and north), direction (front, back, left, right ), these scenes are very suitable for enumeration.

II. The definition of enumeration

The first: the default constructor (the constructor empty)

public enum Quarter {
    SPRING, SUMMER, AUTUMN, WINTER;
}

Undefined member variable and methods are omitted private Quarter () {}

public enum Quarter {
    SPRING, SUMMER, AUTUMN, WINTER;
    private Quarter(){}
}

Briefly explain: Enumeration enum constructor can only be private

The second: the definition of the member variables with argument constructor

You can define enumeration member variables, including members of properties, methods, abstract methods, static methods, etc.

public enum Quarter {
    SPRING("春"), SUMMER("夏"), AUTUMN("秋"), WINTER("冬");

    private Quarter(String name){
        this.name = name;
    }
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    //静态方法
    public static void printName(){
        System.out.println(Quarter.SUMMER);
    }
    
    //抽象方法
    public abstract void printValue();
}

Note: enumeration and classes, there may be a plurality of configuration, i.e. with a parameterized constructor, no-argument constructor may be, can be by the compiler.

In addition:

  1. Enumeration enum java.lang.Enum default inherits class, and implements java.lang.Seriablizable java.lang.Comparable two interfaces, and comparing serializable;
  2. All enumeration values ​​are constants, default to a public static final was modified, enum class is not, naturally can not be inherited or achieved;
  3. Enum values ​​must be in the first row, or compiler errors;

III. Enumeration common usage

1. Obtain an enumeration member variables and elements

static void main public (String [] args) { 
    // Get enumeration element 
    System.out.println (Quarter.SPRING); 
    // call toString () method of enumerated elements into String type 
    System.out.println (Quarter .SPRING.name ()); 
    System.out.println (Quarter.SPRING.toString ()); 
    // get the member variables 
    System.out.println (Quarter.SPRING.getName ()); 
}

Output:

SPRING
SPRING
SPRING
春

2. enumeration traversal

Sometimes we need to enumerate the elements are taken out as a query, then you need is traversed by calling Quarter.values ​​() method

static void main public (String [] args) { 
    // by values () method to obtain an array element Quarter 
    Quarter [] = Quarter.values Quarters (); 
    List <String> = new new quarterParam the ArrayList <> (quarters.length); 
    // the array elements stored in the List quarterParam set 
    for (Quarter Quarter: Quarters) { 
        quarterParam.add (quarter.toString ()); 
    } 
}

3. switch condition determination

Enumerated elements is limited and fixed, by doing conditional switch is just

static void main public (String [] args) { 
    Quarter Quarter = Quarter.AUTUMN; 
    Switch (Quarter) { 
        Case SPRING: 
            System.out.println ( "found, it is:" + SPRING); 
            BREAK; 
        Case SUMMER: 
            the System .out.println ( "found, it is:" + SUMMER); 
            BREAK; 
        Case AUTUMN: 
            System.out.println ( "found, it is:" + AUTUMN); 
            BREAK; 
        Case WINTER: 
            System.out.println ( "found, it is:" + WINTER); 
            BREAK; 
        default: 
            System.out.println ( "not found"); 
            BREAK; 
    } 
}

After the implementation of the results:

Found, is it: AUTUMN

Briefly explain: In fact, the default content is not needed here, or a default would WINTER can, because there are natural enumeration type restrictions, you can only pass it on existing elements and null, but under normal circumstances, would pass judgment in advance the argument is null, null is received when the switch will be reported java.lang.NullPointerException.

4. Comparison of enumeration

4.1. Determine whether the same

Enumeration determines two elements are equal to judge == directly, because it is a non-class can not be instantiated, the storage location is not naturally vary according to the different objects.

public static void main(String[] args){
    System.out.println(Quarter.AUTUMN == Quarter.AUTUMN);
    System.out.println(Quarter.AUTUMN == Quarter.WINTER);
}

Results of the:

true
false

It can also be carried out by equals () method of comparison, but not necessary, because it is through the bottom == achieved.

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
    //equals比较
    public final boolean equals(Object other) {
        return this==other;
    }
}

4.2. Comparison of order

CompareTo enumerated elements by comparison, it is a comparison of the sequence where the element in the enumeration, the number returned is the difference in sequence position

public static void main(String[] args){
    System.out.println(Quarter.AUTUMN.compareTo(Quarter.SPRING));
    System.out.println(Quarter.AUTUMN.compareTo(Quarter.WINTER));
}

Implementation of the results:

2
-1

We look at the compareTo method

the Enum abstract class public <E the extends the Enum <E >> 
        the implements the Comparable <E>, the Serializable { 
    // index of the element in the enumeration 
    Private Final int ordinal; 
    // you can see the difference between two elements is compareTo method returns the ordinal value 
    public int Final the compareTo (E O) { 
        the Enum OTHER = (the Enum <?>) O <?>; 
        the Enum <E> = Self the this; 
        ! IF (self.getClass () = other.getClass () && 
            self.getDeclaringClass ! () = other.getDeclaringClass ()) 
            the throw a ClassCastException new new (); 
        return self.ordinal - other.ordinal; 
    } 
}

The enumeration may also implement an interface

public interface WeatherInterface {
    //获取温度
    public String getTemperature(Quarter quarter);
}
public enum Quarter implements WeatherInterface{
    SPRING("春"), SUMMER("夏"), AUTUMN("秋"), WINTER("冬");
    
    private Quarter(String name){
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }
    //重写获取温度方法
    @Override
    public String getTemperature(Quarter quarter) {
        switch (quarter) {
            case SPRING:
                return "适中";
            case SUMMER:
                return "热";
            case AUTUMN:
                return "凉爽";
            case WINTER:
                return "cold";
            default: 
                return "unable to determine"; 
        } 
    } 
}

But note that the enumeration can not inherit from other classes

Pquarter class {} public 
// not compile 
public enum Quarter extends Pquarter {}

6. use the interface to organize enumerate

If the enumeration too much is not good management, and structured not clear enough, we can enumerate interfaces to multiple related organizations together to manage,

public interface Weather {
    enum Quarter implements Weather {
        SPRING, SUMMER, AUTUMN, WINTER;
    }
    enum Temperature implements Weather {
        MODERATE, HEAT, COOL, COLD
    }
    //调用时直接通过Weather.Quarter.SPRING即可。
}

IV. Summary

This paper describes the main features of enum enumeration, definitions, common methods, no arguments constructor, there are arguments constructor, for example, and enumerated the main scenario, if imperfect, please criticism and hope to make progress together, thank you!

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160017.htm