47
votes

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?

6
Are you talking about enums or an Enumeration ? These are not the same.Cyrille Ka
Was talking about enums. Problem is that in french enums is a shorthand for "enumeration".(as in english I tend to think). so wasn't speaking of the interface.AdrieanKhisbe
Is it OK that I added the Kotlin tag? I Googled a Kotlin solution and ended up here.Mahozad
Refer to this related post.Mahozad

6 Answers

75
votes

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) {
        System.out.println(WORKDAYS.values().length);
        // prints 5
    }
}

http://ideone.com/zMB6pG

13
votes

You can get the length by using Myenum.values().length

The Enum.values() returns an array of all the enum constants. You can use the length variable of this array to get the number of enum constants.

Assuming you have the following enum:

public enum Color
{
    BLACK,WHITE,BLUE,GREEN,RED
}

The following statement will assign 5 to size:

int size = Color.values().length;
5
votes

The enum.values() method is added by the Java complier and is not mentioned in the APIs.

Where is the documentation for the values() method of Enum?

3
votes

MyEnum.values() returns the enum constants as an array.

So you can use:

int size = MyEnum.values().length
2
votes

To avoid calling values() method each time:

public class EnumTest {

    enum WORKDAYS {
       Monday,
       Tuesday,
       Wednesday,
       Thursday,
       Friday;

       public static final int size;
       static {
          size = values().length;
       }
   }


   public static void main(String[] args) {
      System.out.println(WORKDAYS.size); // 5
   }
}
0
votes

I searched for a Kotlin answer and this question popped up. So, here is my answer.

enum class MyEnum { RED, GREEN, BLUE }
MyEnum.values().size // 3

This is another way to do it:

inline fun <reified T : Enum<T>> sizeOf() = enumValues<T>().size
sizeOf<MyEnum>() // 3

Thanks to this answer.