Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 536
steffen Avatar asked Mar 18 '26 01:03

steffen


1 Answers

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.

like image 182
yole Avatar answered Mar 20 '26 14:03

yole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!