Enumeration types of Java Foundation

Posted by Schlo_50 on Tue, 23 Jun 2020 11:28:19 +0200

Before the introduction of enumeration types in Java, we often defined global constants in the way of abstract classes, for example:

public abstract class UploadStatus {
    public static final int UPLOAD_IN_PROGRESS = 0;
    public static final int UPLOAD_FAILED = 1;
    public static final int UPLOAD_SUCCEEDED = 2;
}

Now we can use enumeration types to define:

enum UploadStatusEnum {
    UPLOAD_IN_PROGRESS, UPLOAD_FAILED, UPLOAD_SUCCEEDED
}

Enumeration itself is a class, and it inherits from java.lang.Enum . Upload defined in enumeration class_ IN_ PROGRESS, UPLOAD_ FAILED, UPLOAD_ Succeeded can be understood as an instance of UploadStatusEnum (globally unique single instance) (when defining enumeration properties, it is required to be defined at the front end). Next, let's look at the properties and methods of enumeration types:

public class TestEnum {
    public static void main(String[] args) {
        System.out.println(UploadStatusEnum.UPLOAD_IN_PROGRESS);
        System.out.println(UploadStatusEnum.UPLOAD_FAILED);
        System.out.println(UploadStatusEnum.UPLOAD_SUCCEEDED);
        for (UploadStatusEnum uploadStatus : UploadStatusEnum.values()) {
            System.out.println("name is " + uploadStatus.name() + " ordinal is " + uploadStatus.ordinal() + " toString is " + uploadStatus.toString());
        }
        UploadStatusEnum copyEnum = UploadStatusEnum.UPLOAD_IN_PROGRESS;
        System.out.println(copyEnum == UploadStatusEnum.UPLOAD_IN_PROGRESS);
        System.out.println(copyEnum.equals(UploadStatusEnum.UPLOAD_IN_PROGRESS));
    }

    enum UploadStatusEnum {
        UPLOAD_IN_PROGRESS, UPLOAD_FAILED, UPLOAD_SUCCEEDED
    }
}

The output is as follows:

From the above code, we can know the following points:

(1) We can go straight through UploadStatusEnum.UPLOAD_ IN_ The specific enumeration objects are obtained by the way of progress;

(2) Calling the toString method of the object returns the literal string of enumeration property: UPLOAD_IN_PROGRESS´╝Ť

(3) We can go through UploadStatusEnum.values() static method to traverse enumeration objects;

(4) By enumerating the name() method of the object, you can also get the literal string of the enumerating property (the result is consistent with the toString method);

(5) The integer value assigned to the enumeration object can be obtained by the ordinal() method of the enumeration object, starting from 0 in the order of declaration;

(6) Enumeration objects can be compared directly by = = or equals();

Knowing the above points can basically satisfy most of the situations in which we use enumeration in development.

Here are some other uses of enumeration:

1. Custom constructors and other methods in enumeration class:

enum UploadStatusEnum {
        UPLOAD_IN_PROGRESS, UPLOAD_FAILED, UPLOAD_SUCCEEDED;  // Enumeration classes must add semicolons if they want to customize constructors, methods, etc., and the declaration of enumeration properties must still be at the top
        private int value;
        private String description;

        private UploadStatusEnum(int value, String description) {
            this.value = value;
            this.description = description;
        }
}

The above code defines a private constructor for the enumeration class (the constructor of the enumeration class must be declared private). But at this time, our IDE will report an error:

Expected 2 arguments but found 0

It indicates that our custom constructor causes the default constructor to fail, so we must modify the definition method of enumeration property:

enum UploadStatusEnum {
    UPLOAD_IN_PROGRESS(0, "uploading"), UPLOAD_FAILED(1, "upload failed"), UPLOAD_SUCCEEDED(2, "upload successfully");
    private int value;
    private String description;

    private UploadStatusEnum(int value, String description) {
        this.value = value;
        this.description = description;
    }
}

You can also customize methods in enumeration classes and override methods in the parent class Enum, for example:

enum UploadStatusEnum {
    UPLOAD_IN_PROGRESS(0, "uploading"), UPLOAD_FAILED(1, "upload failed"), UPLOAD_SUCCEEDED(2, "upload successfully");
    private int value;
    private String description;

    private UploadStatusEnum(int value, String description) {
        this.value = value;
        this.description = description;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "UploadStatusEnum{" +
                "value=" + value +
                ", description='" + description + '\'' +
                '}';
    }
}

Call the corresponding method by enumerating instances:

System.out.println(UploadStatusEnum.UPLOAD_IN_PROGRESS.getDescription());  // uploading

From the above code, we can see that the behavior of enumeration class is basically the same as that of ordinary class. Enumeration properties can also be understood as singleton objects.

2. Implementation interface

Because enumeration classes already inherit from java.lang.Enum Class, so enumeration classes can no longer inherit other classes. However, enumeration classes can also implement interfaces and corresponding methods.

3. Enumeration set

There are two classes in the enumeration collection: java.util.EnumSet (elements are enumeration objects, and they are not repeated) and java.util.EnumMap (similar to HashMap, key is an enumeration object, and the value can be any type declared.).

EnumSet is an abstract class and cannot be instantiated:

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
    implements Cloneable, java.io.Serializable

But we can call its static method:

EnumSet<UploadStatusEnum> statusEnums = EnumSet.allOf(UploadStatusEnum.class);
for (UploadStatusEnum status : statusEnums) {
    System.out.println(status);
}

The output is as follows:

EnumMap is a class inherited from abstractmap < K, V >

public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
    implements java.io.Serializable, Cloneable

The usage method is similar to HashMap, for example:

EnumMap<UploadStatusEnum, String> enumMaps = new EnumMap<UploadStatusEnum, String>(UploadStatusEnum.class);
enumMaps.put(UploadStatusEnum.UPLOAD_IN_PROGRESS, "uploading_0");
enumMaps.put(UploadStatusEnum.UPLOAD_FAILED, "uploadFailed_1");
enumMaps.put(UploadStatusEnum.UPLOAD_SUCCEEDED, "uploadSuccess_2");

for (Map.Entry<UploadStatusEnum, String> entry : enumMaps.entrySet()) {
    System.out.println("key is " + entry.getKey() + " value is " + entry.getValue());
}

The output results are as follows:

That's all about java enumeration~

Topics: Java