I have a enum SOME_ENUM
:
public enum SOME_ENUM { EN_ONE, EN_TWO, EN_THREE; }
Will SOME_ENUM.values()
always return the enums in the order of enum declarations: EN_ONE, EN_TWO, EN_THREE
? Is it a rule or it is not guaranteed to be not changed in the next JDK releases?
values() is a static method of Enum , which always returns the values in same order.
A: Ordinal method returns the order in which Enum instance are declared inside Enum. For example in a DayOfWeek Enum, you can declare days in order they come e.g. Ordinal arranges or assigns numbers to each element in Enum starting from 0.
1. What is the order of variables in Enum? Explanation: The compareTo() method is implemented to order the variable in ascending order.
By default enums have their own string values, we can also assign some custom values to enums.
The Java language specification uses this explicit language:
@return an array containing the constants of this enum type, in the order they're declared [Source]
So, yes, they will be returned in declaration order. It's worth noting that the order might change over time if someone changes the class so be very careful about how you use this.
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