java EnumSet,不兼容的类型:推理变量E具有不兼容的边界



>我有一个以下方法,它返回一个包含Types所有元素的枚举集:

@Override
public EnumSet<?> groupTypes() {
    return EnumSet.allOf(Types.class);
}

Types是如下所示的enum

public enum Types implements GroupType {
    ASG;
}

GroupType界面为:

 public interface GroupType extends NamedType {
 }

NamedType界面:

public interface NamedType {
    String name();
}

编译时,我收到以下错误:

    error: incompatible types: inference variable E has incompatible bounds
return EnumSet.allOf(Types.class);
                        ^
equality constraints: Types
    upper bounds: Enum<CAP#1>,Enum<E>
  where E is a type-variable:
    E extends Enum<E> declared in method <E>allOf(Class<E>)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Enum<CAP#1> from capture of ?

错误

错误:不兼容的类型:推理变量 E 不兼容 bounds 返回 EnumSet.allOf(Types.class);

告诉你问题出在哪里。一种解决方法是像这样更改签名

public EnumSet<? extends NamedType> groupTypes() {
        return EnumSet.allOf(Types.class);
    }

或者你可以只EnumSet.allOf(Types.class)赋值给一个变量,然后就不需要像这样更改方法签名了

public EnumSet<?> groupTypes() {
    EnumSet<Types> typeses = EnumSet.allOf(Types.class);
    return typeses;
}

最新更新