How to get number of possible items of an Enum?
Solution 1
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
}
}
Solution 2
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
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?
Solution 4
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
MyEnum.values()
returns the enum constants as an array.
So you can use:
int size = MyEnum.values().length
AdrieanKhisbe
Software Engineer Looking for a GREAT TEAM Curious, Craftman, Polyglot, #franc et #french API with @hapijs & μS @senecajs, tooling around with @spacemacs
Updated on October 14, 2021Comments
-
AdrieanKhisbe over 2 years
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? -
Cyrille Ka almost 11 years
length
is not a method of an array, it is a property field, so you'd use it without parentheses. -
Rahul Bobhate almost 11 years@CyrilleKa: Thanks for notifying. Corrected it. :)
-
Mark Jeronimus over 4 years
Enum.values()
allocates a new array every time so it's not recommended for high call rate (i.e. for-loop condition). Cache the value if you need to call it very often. -
Hatefiend over 3 years@MarkJeronimus Even without calling it often, this is still bad practice. Allocating an array just for the length property is silly, even if only done once.
-
Bouh about 3 years@Hatefiend so what do you suggest?
-
Mahozad over 2 yearsSee this Kotlin issue aiming to replace
Enum.values()
with a more modern and performant alternative.