4

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
  • It's not possible Commented Jun 7, 2021 at 18:20

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. But when I compare this approaches, second looks clearer: 1) boolean match = EnumSet.of(Fruit.APPLE, Fruit.CHERRY).contains(fruit); 2) boolean match = fruit.in(Fruit.APPLE, Fruit.CHERRY);
@AndreiYusupau I don't think you can make it type safe using your approach. Your interface may be implemented by a regular class rather than an enum. One thing to note is that you don't really need the cast in the contains() method, you can just do .contains(this);.
If it happens so that this won't be of type T without cast it would just silently return false, but with cast it would be an ClassCastException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.