Java enum order: ordinal(), compareTo() and custom ordering
Codemia Knowledge Hub ·
A Java enum already stores an ordering: the order in which its constants are declared. ordinal() returns a constant's zero-based position, compareTo() compares by that position, and Arrays.sort() or Collections.sort() use it as the natural order. When you need a different order, sort with a Comparator.
Enum basics
Enums define a fixed set of related constants:
Key characteristics:
- Type safety: enums provide type safety and a unique namespace for their constants.
- Implicit modifiers: enum constants are implicitly
public,staticandfinal. - Methods and fields: enums can have methods and fields like regular classes.
- Built-in ordering: every enum has an
ordinal()method that returns the constant's position in the declaration, starting from 0, and enums areComparable.
Storing extra data on each constant
Enums can carry additional information in fields. Here each day has an associated activity:
getActivity() returns the value for each constant.
Declaration order with ordinal() and compareTo()
ordinal() gives a constant's position:
THURSDAY has an ordinal of 4.
compareTo() compares two constants by ordinal:
Sorting enums
Because enums have a natural ordering, sorting an array or list needs no extra code:
Custom ordering with a Comparator
When declaration order is not the order you want, pass a Comparator:
daysList is now sorted by the associated activity.
Quick reference
| Feature | Description | Example |
| Natural ordering | Defined by declaration order (using ordinal()) | MONDAY.ordinal() returns 1 |
| Comparison | compareTo() compares ordinal() values | MONDAY.compareTo(WEDNESDAY) |
| Sorting | Uses natural ordering by default | Arrays.sort(Day.values()) |
| Custom ordering | Implement with Comparator | Compare by activity |
| Additional data | Enums can store extra info in fields | private final String activity in Day enum |
Related reading
- Storm Topology Rebalance Using Java Code
- Strange OutOfMemory issue while loading an image to a Bitmap object
- StreamCorruptedException invalid type code AC
- String concatenation concat() vs + operator
- String representation of an Enum
- String, StringBuffer, and StringBuilder
- String variable interpolation Java
- String vs. StringBuilder
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.