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 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