Paul Boddington
Paul Boddington

Reputation: 37645

static methods that take Enum parameters

I find it extremely difficult to write static methods that work for Enums. It's a really contrived example, but suppose you want to write a method that takes an Enum constant and returns the next declared one. I found (after about an hour) that you can do it as follows. It works, and doesn't generate any compiler warnings.

static <E extends Enum<E>> E getNextDeclared(E e) {
    int ordinal = e.ordinal();
    for (Object object : EnumSet.allOf(e.getClass())) {
        if (e.getClass().cast(object).ordinal() == ordinal + 1) {
            return e.getDeclaringClass().cast(object);
        }
    }
    throw new IllegalArgumentException();
}

Am I missing something? Can you do it without casts? Is there any way to simplify this without generating a load of warnings? Also what is the appropriate class to write in place of Object?

Upvotes: 0

Views: 110

Answers (1)

Jesper
Jesper

Reputation: 206786

Like this:

static <E extends Enum<E>> E getNextDeclared(E e) {
    int ordinal = e.ordinal();
    for (E object : EnumSet.allOf(e.getDeclaringClass())) {
        if (object.ordinal() == ordinal + 1) {
            return object;
        }
    }
    throw new IllegalArgumentException();
}

or, with what Louis Wasserman suggests:

static <E extends Enum<E>> E getNextDeclared(E e) {
    return e.getDeclaringClass().getEnumConstants()[e.ordinal() + 1];
}

(although that would throw an ArrayIndexOutOfBoundsException instead of an IllegalArgumentException if you go too high).

Upvotes: 1

Related Questions