Search code examples
javagenericsenumset

Adding type argument to EnumSet always give me "Bound mismatch"


I have this code below:

public static <E> Set<E> union(Set<E> set1, Set<E> set2) {
    Set<E> resultSet = new HashSet<>(set1);
    resultSet.addAll(set2);
    return resultSet;
}

I want to overload one method like below, and get bound mismatch:

 public static <E> Set<E> union(EnumSet<E extends Enum<E>> set1, EnumSet<E extends Enum<E>> set2){
    Set<E> resultSet = set1.clone();
    resultSet.addAll(set2);
    return resultSet;
}

And I change to below, and it doesn't work.

Why? And how can I do?


Solution

  • The class EnumSet is declared as following

    public abstract class EnumSet<E extends Enum<E>> extends ... implements ... { ... }
    

    Here you can see that the type variable E is constrained to being a subtype of Enum<E>. Hence, you must constrain the type variable of your static method in the same way:

    public static <E extends Enum<E>> Set<E> union(EnumSet<E> set1, EnumSet<E> set2) {
        Set<E> resultSet = set1.clone();
        resultSet.addAll(set2);
        return resultSet;
    }