Java Enum ordinal()

www.laut‮moc.irut‬
Java Enum ordinal()

In Java, the ordinal() method is a member of the Enum class, which is the superclass of all enum types. The ordinal() method returns the position of an enum value in the values array of the enum type, with the first value having an ordinal of zero.

Here's an example of how to use the ordinal() method with an enum in Java:

public enum Size {
    SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

    private String abbreviation;

    private Size(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static void main(String[] args) {
        Size s1 = Size.SMALL;
        Size s2 = Size.LARGE;

        int ordinal1 = s1.ordinal();  // ordinal1 is 0
        int ordinal2 = s2.ordinal();  // ordinal2 is 2
        System.out.println(ordinal1);
        System.out.println(ordinal2);
    }
}

In this example, the Sizeenum has four constant values: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. The ordinal() method is called on the SMALL and LARGE constants and the returned ordinals are assigned to the ordinal1 and ordinal2 variables, respectively.

You can use the ordinal() method to get the position of an enum value in the values array of the enum type. The ordinal() method is useful for sorting enum values or for comparing them in other contexts.

Created Time:2017-11-03 15:57:10  Author:lautturi