steffen
steffen

Reputation: 16948

Create an enum set of generic type

How can I create an empty EnumSet when I don't have the runtime type of the generic enum? Example code:

public class Utility<T extends Enum<T>> {
    private T[] enumConstants;
    public Utility(Class<T> e) {
        enumConstants = e.getEnumConstants();
    }
    private EnumSet<T> emptyEnumSet() {
        // ?
    }
}

Here's my current workaround, I think it comes a bit clumsy:

private EnumSet<T> emptyEnumSet() {
    T first = enumConstants[0];
    EnumSet<T> result = EnumSet.of(first);
    result.remove(first);
    return result;
}

Upvotes: 3

Views: 964

Answers (1)

yole
yole

Reputation: 97168

EnumSet.noneOf() should do what you need. Your code receives the Class<T> as the constructor parameter, so you'd need to store it in a field.

Upvotes: 6

Related Questions