How to get number of possible items of an Enum?

JavaKotlinEnums

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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;

Solution 3 - Java

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

https://stackoverflow.com/questions/13659217/values-method-of-enum

Solution 4 - Java

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
   }
}

Solution 5 - Java

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

So you can use:

int size = MyEnum.values().length

Solution 6 - Java

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 Miha_x64 for this answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdrieanKhisbeView Question on Stackoverflow
Solution 1 - JavaHunter McMillenView Answer on Stackoverflow
Solution 2 - JavaRahul BobhateView Answer on Stackoverflow
Solution 3 - JavajaamitView Answer on Stackoverflow
Solution 4 - JavaYevhen TkachenkoView Answer on Stackoverflow
Solution 5 - JavaPuceView Answer on Stackoverflow
Solution 6 - JavaMahozadView Answer on Stackoverflow