gpt4 book ai didi

java - 无法从枚举转换为它实现的接口(interface)

转载 作者:搜寻专家 更新时间:2023-11-01 04:02:46 25 4
gpt4 key购买 nike

我在 Java 7 中,我有以下枚举:

public enum BooleanEnum implements StringRepresentable{
YES {
@Override
public String getStringRepresentation() {
return "true";
}
},
NO {
@Override
public String getStringRepresentation() {
return "false";
}
};
public abstract String getStringRepresentation();
}

现在我有了方法:

List<StringRepresentable> getValues(){
return Arrays.asList(BooleanEnum.values()); //Type mismatch:
//cannot convert from List<BooleanEnum> to List<StringRepresentable>
}

enum 有什么问题?它实现了接口(interface),因此代码应该可以正常编译。

最佳答案

It implements the interface, therefore the code should have compiled fine.

不,因为类型参数被推断为 BooleanEnum - 和一个 List<BooleanEnum>不是 List<StringRepresentation> ...您可以添加 other 的实例 StringRepresentation后者的实现。

四种可能的选择:

  • 指定您要返回 StringRepresentation 的某个子类的列表:

    List<? extends StringRepresentation> get Values() {
    // Implementation as before
    }
  • 指定参数类型:

    return Arrays.<StringRepresentation>asList(BooleanEnum.values());
  • 为清楚起见,使用中间变量:

    StringRepresentation[] array = BooleanEnum.values();
    return Arrays.asList(array);
  • 不要返回 List<StringRepresentation>根本;返回 Iterable<StringRepresentation>此时您可以使用 EnumSet相反:

    Iterable<? extends StringRepresentable> getValues() {
    return EnumSet.allOf(BooleanEnum.class);
    }

关于java - 无法从枚举转换为它实现的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29604929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com