Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum.values() - is an order of returned enums deterministic

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?

like image 693
Skarab Avatar asked Sep 29 '10 09:09

Skarab


People also ask

Is enum values ordered?

values() is a static method of Enum , which always returns the values in same order.

What method returns the order in which enum?

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.

What is the order of variables in enum?

1. What is the order of variables in Enum? Explanation: The compareTo() method is implemented to order the variable in ascending order.

Can you give enums values?

By default enums have their own string values, we can also assign some custom values to enums.


Video Answer


1 Answers

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.

like image 193
GaryF Avatar answered Sep 28 '22 04:09

GaryF