What’s the best way to implement `next` and `previous` on an enum type?

Try this:

public enum A {
    X, Y, Z;
    
    private static final A[] vals = values();
    
    public A next() {
        return vals[(this.ordinal() + 1) % vals.length];
    }
}

Implementation of previous() is left as an exercise, but recall that in Java, the modulo a % b can return a negative number.

EDIT: As suggested, make a private static copy of the values() array to avoid array copying each time next() or previous() is called.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)