Home > Java > javaTutorial > body text

What are the methods that come with Java enumeration classes?

王林
Release: 2023-04-24 21:55:06
forward
1285 people have browsed it

1. valueOf() method

This is a static method that passes in a string (the name of the enumeration) to get the enumeration class. If the name passed in does not exist, an error will be reported.

public static void main(String[] args) throws Exception{
    System.out.println(PayTypeEnum.valueOf("ALI_PAY"));
    System.out.println(PayTypeEnum.valueOf("HUAWEI_PAY"));
}
Copy after login

2. values() method

Returns an array containing all enumeration data in the enumeration class.

public static void main(String[] args) throws Exception {
    PayTypeEnum[] payTypeEnums = PayTypeEnum.values();
    for (PayTypeEnum payTypeEnum : payTypeEnums) {
        System.out.println("code: " + payTypeEnum.getCode() + ",describe: " + payTypeEnum.getDescribe());
    }
}
Copy after login

3. ordinal() method

By default, the enumeration class will provide a default order for the defined enumeration, and the ordinal() method can Returns the order of the enumeration.

public static void main(String[] args) throws Exception {
    PayTypeEnum[] payTypeEnums = PayTypeEnum.values();
    for (PayTypeEnum payTypeEnum : payTypeEnums) {
        System.out.println("ordinal: " + payTypeEnum.ordinal() + ", Enum: " + payTypeEnum);
    }
}
/**
ordinal: 0, Enum: ALI_PAY
ordinal: 1, Enum: WECHAT_PAY
ordinal: 2, Enum: UNION_PAY
*/
Copy after login

The above is the detailed content of What are the methods that come with Java enumeration classes?. 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