Java
Enums
Ordering
Programming
Development

Store an ordering of Enums in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Enums in Java: Storing and Ordering

Enums in Java are a special kind of Java class used to define collections of constants. They are implicitly final and static, meaning you cannot create subclasses of enums and can't modify enums instance fields directly. An enum class is a specialized class that is a full-fledged member of the Java type system. This article delves into the nuances of storing and ordering enums, enhancing your understanding with technical explanations, examples, and a summary table.

Basics of Enums

Enums are often used when you have a fixed set of related constants. Consider the following simple enum declaration:

java
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Key Characteristics of Enums:

  1. Type Safety: Enums provide type safety and a unique namespace for their constants.
  2. Implicit static and final: Enum constants are implicitly public, static, and final.
  3. Methods and Fields: Enums can have methods and fields just like regular classes.
  4. Enums are Comparable: Every enum in Java has a built-in ordinal() method, which returns the position of the enum constant in the enum declaration, starting from 0.

Storing Enums in Java

Enums can store additional information using fields. Let's consider an example where each day of the week is associated with an activity:

java
1public enum Day {
2    SUNDAY("Rest"), MONDAY("Work"), TUESDAY("Work"),
3    WEDNESDAY("Work"), THURSDAY("Work"), FRIDAY("Work"),
4    SATURDAY("Leisure");
5
6    private final String activity;
7
8    Day(String activity) {
9        this.activity = activity;
10    }
11
12    public String getActivity() {
13        return activity;
14    }
15}

Here, each day is associated with an activity. You can retrieve this information with the getActivity() method.

Ordering Enums

Ordering in enums can be achieved by utilizing their natural order defined by the order they are declared in. Java provides an ordinal() method that allows you to determine an enum constant's ordinal position. Enum constants can also be compared using the compareTo() method, which compares based on ordinal values.

Example of Ordering with ordinal():

java
Day today = Day.THURSDAY;
System.out.println("Ordinal of " + today.name() + ": " + today.ordinal());

In this example, THURSDAY will have an ordinal value of 4.

Example of Ordering with compareTo():

java
1Day d1 = Day.MONDAY;
2Day d2 = Day.WEDNESDAY;
3int comparison = d1.compareTo(d2);
4
5if (comparison < 0) {
6    System.out.println(d1 + " comes before " + d2);
7} else {
8    System.out.println(d1 + " comes after or is the same as " + d2);
9}

Sorting Enums

In scenarios where you need to sort an array or list of enums, using Arrays.sort() or Collections.sort() is straightforward due to the natural ordering provided by compareTo():

java
1Day[] days = Day.values();
2Arrays.sort(days);
3for (Day day : days) {
4    System.out.println(day);
5}

Custom Ordering of Enums

Sometimes, the natural order is not suitable, and a custom order is required. This can be done by implementing Comparator:

java
Comparator<Day> customComparator = (d1, d2) -> d1.getActivity().compareTo(d2.getActivity());
List<Day> daysList = Arrays.asList(Day.values());
Collections.sort(daysList, customComparator);

In this case, daysList will be sorted based on the associated activity.

Summary Table

FeatureDescriptionExample
Type SafetyProvides type safety and unique namespaceDay.SUNDAY
Implicit PropertiesEnum constants are public, static, final-
Methods & FieldsEnums can have methods and fieldssee Day example
Natural OrderingDefined by declaration order (using ordinal())MONDAY.ordinal() returns 1
ComparisonSupports compareTo(), compares ordinal() valuesMONDAY.compareTo(WEDNESDAY)
SortingUses natural ordering by defaultArrays.sort(Day.values())
Custom OrderingImplement with ComparatorCompare by activity
Storage with Additional DataEnums can store additional info using fieldsprivate final String activity in Day enum

Enums, by their design, ensure robustness and clarity. They provide a structured way to represent fixed sets of constants. When you need to store additional states or leverage custom orderings, enums offer the flexibility to accommodate these needs efficiently. Understanding how to manipulate and use enums effectively can lead to cleaner and more maintainable codebases.


Course illustration
Course illustration

All Rights Reserved.