How to get number of possible item of an Enum?

Is there a builtin way to get the number of items of an Enum with something like Myenum.length,

Or do I have to implement myself a function int size() hardcording the number of element?


Yes you can use the Enum.values() method to get an array of Enum values then use the length property.

public class Main {
    enum WORKDAYS { Monday, Tuesday, Wednesday, Thursday, Friday; }

    public static void main(String[] args) {
        // prints 5

Leave a Reply

Your email address will not be published. Required fields are marked *