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) {
System.out.println(WORKDAYS.values().length);
// prints 5
}
}
http://ideone.com/zMB6pG
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With