Close

Java - How to get next or previous enum constant by a current instance?

[Last Updated: May 25, 2018]

Java Enum 

Following example shows how to get next or previous enum constant via instance methods. We are going to define an interface with default methods which will be implemented by an enum to have this functionality.

package com.logicbig.example;

public interface IEnum<E extends Enum<E>> {

  int ordinal();

  default E next() {
      E[] ies = this.getAllValues();
      return this.ordinal() != ies.length - 1 ? ies[this.ordinal() + 1] : null;
  }

  default E previous() {
      return this.ordinal() != 0 ? this.getAllValues()[this.ordinal() - 1] : null;
  }

  @SuppressWarnings("unchecked")
  private E[] getAllValues() {//java 9 private methods in interface
      IEnum[] ies = this.getClass().getEnumConstants();
      return (E[]) ies;
  }
}
package com.logicbig.example;

public class NextPrevExample {
  enum Car implements IEnum<Car> {
      Cadillac, Dodge, Chevrolet, Ferrari
  }

  public static void main(String[] args) {
      System.out.println(" -- next test --");
      Car car = Car.Cadillac;
      car = car.next();
      System.out.println(car);
      while ((car = car.next()) != null) {
          System.out.println(car);
      }

      System.out.println(" -- prev test --");
      car = Car.Ferrari;
      while ((car = car.previous()) != null) {
          System.out.println(car);
      }
  }
}
 -- next test --
Dodge
Chevrolet
Ferrari
-- prev test --
Chevrolet
Dodge
Cadillac

See Also