Home > Java > javaTutorial > What is the principle of java enumeration type

What is the principle of java enumeration type

WBOY
Release: 2023-04-19 19:07:11
forward
1212 people have browsed it

Explanation

1. Java has added the java.lang.Enum abstract class, which is the base class for all enumeration types. Provides basic properties and basic methods. At the same time, it supports using enumerations as Sets and Maps

2. After using the keyword enum to create an enumeration type and compile it, the compiler will generate a related category for us, which inherits java.lang .Enum class.

Example

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
 
    // 枚举的常量名,例如MONDAY, TUESDAY
    private final String name;
 
    public final String name() {
        return name;
    }
 
    // 枚举的序号,按顺序从0开始
    private final int ordinal;
 
    public final int ordinal() {
        return ordinal;
    }
 
    protected Enum(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
    }
 
    public String toString() {
        return name;
    }
    
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                                String name) {
        T result = enumType.enumConstantDirectory().get(name);
        if (result != null)
            return result;
        if (name == null)
            throw new NullPointerException("Name is null");
        throw new IllegalArgumentException(
            "No enum constant " + enumType.getCanonicalName() + "." + name);
    }
    ...
}
Copy after login

The above is the detailed content of What is the principle of java enumeration type. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template