Enum class implicitly implements the Comparable interface to enforce a natural ordering among constants. The natural order is based on the order in which the enum constants are declared. When you create an enum, each of its constants is implicitly comparable to the others.
In the above enum class, natural order is: SUNDAY
, MONDAY
, TUESDAY
, WEDNESDAY
, THURSDAY
, FRIDAY
, SATURDAY
; they have corresponding position starting from 0
for SUNDAY
, 1
for MONDAY
and continue on.
You can use ordinal()
enum method to return the ordinal of this enumeration constant.
1
The compareTo()
method overridden from the Comparable
interface uses these ordinal values to compare the constants.
-1
It compares the ordinal values of day1
and day2
. In this case, day1
MONDAY
has a ordinal value of 1
; day2
WEDNESDAY
has a ordinal value of 3
. Since is less than , the compareTo()
method returns a negative value -1
.
Traverse enum constants
The Java compiler provides a static values()
method for all enum types, you don’t need to define this method as it is implicitly provided. It returns an array containing all the constants of the enum type, in the order they were declared.
You can traverse all the enum constants using a loop.
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
You can access a particular element using its index.
Working with switch statement
Conditional statements like if
and switch
are useful for executing different task for each choice. Below is are examples of using switch case statement for enums.
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaEnumNatural_OrderingComparable