作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在 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/
我是一名优秀的程序员,十分优秀!