Enum default methods

Viewed 140

I'm trying to add a default method for some of my enums using an interface with default method. The method should check if enum is in array(varargs) of enum values.

  1. First warning I get is "Possible heap pollution from parameterized vararg type", but it's not in case of enum, cause it's final, right?
  2. Second warning is "Unchecked cast: BaseEnum<E> to E" (and "Suspicious call" warning witout cast). It also would be safe until I pass right type parameter when implementing my interface. Here is my example code:
public interface BaseEnum<E extends Enum<E>> {

    @SuppressWarnings("unchecked")
    default boolean in(E ... statuses){
        return Arrays.asList(statuses)
                .contains((E) this);
    }
}

public enum Transport implements BaseEnum<Transport> {
    CAR, BUS, PLANE
}

public enum Fruit implements BaseEnum<Fruit> {
    APPLE, CHERRY, LEMON
}

With this implementations everything looks safe. But how can I prevent something like this?(By 'prevent' I mean some code restrictions)

public enum Transport implements BaseEnum<Fruit> {
    CAR, BUS, PLANE
}

I've looked at new Java 15 sealed feature, but seems its not the case. Is there any cleaner solution?

1 Answers

There is no need to create an interface for such an operation. The EnumSet class serves this purpose:

Fruit fruit = ...;
boolean match = EnumSet.of(Fruit.APPLE, Fruit.CHERRY).contains(fruit);
Related