Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of member fields in Enum

Tags:

java

enums

Why the order of declaration important for Java enums, I mean why does this give (compile time) errors

public enum ErrorCodes {
    public int id;
    Undefined;
}

but this one is fine:

public enum ErrorCodes {
    Undefined;
    public int id;

}.
like image 438
anergy Avatar asked Jan 24 '11 09:01

anergy


People also ask

What is the order of the variables in enum?

1. What is the order of variables in Enum? Explanation: The order of appearance of variables in Enum is their natural order (the natural order means the order in which they are declared inside Enum type). However, the compareTo() method is implemented to order the variable in ascending order.

Does order matter in enum?

the difference with enum is that the order of the members matters. To implement this feature the compiler team would have to add new features that would explicitly specify that behavior.

Does enum values () maintain order?

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

How do you sort an enum?

We can use the natural sort order or sort by their properties. Any Enum type we create implements the Comparable interface. Below is an excerpt from the Java documentation. Enum<E> implements Comparable<E> via the natural order of the enum (the order in which the values are declared).


2 Answers

It's not a very satisfying answer, but it's just how enums are defined in Java. See section 8.9 Enums in The Java Language Specification.

like image 150
Jesper Avatar answered Oct 14 '22 14:10

Jesper


Because this is the syntax for enums. It could allow different orders however this may have been open to mistakes such as forgetting to place a type on a field and turning it into a enum value.

EDIT: The reason I say they could be in any order is that fields, methods, initialisers and constructors can be in any order. I believe the restriction is valid if it is to reduce mistakes. Even though fields/constructors/methods can be in any order its very common to see them in that order for readability.

like image 38
Peter Lawrey Avatar answered Oct 14 '22 16:10

Peter Lawrey