Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of possible items of an Enum?

Tags:

java

enums

kotlin

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?

like image 923
AdrieanKhisbe Avatar asked Jul 05 '13 15:07

AdrieanKhisbe


2 Answers

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

like image 76
Hunter McMillen Avatar answered Oct 14 '22 00:10

Hunter McMillen


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;
like image 13
Rahul Bobhate Avatar answered Oct 14 '22 02:10

Rahul Bobhate