【问题标题】:Combining Java Enum and Generics结合 Java 枚举和泛型
【发布时间】:2017-09-05 02:22:29
【问题描述】:

我正在尝试使用泛型和枚举来设计一段代码。我希望使用原始整数来获取枚举,并且它必须包含一个字符串。我有很多枚举,所以我用一个接口实现了它们,以便记住覆盖公共toString()getIndex()getEnum() 方法。但是,我收到了类型安全警告,知道如何摆脱它以及为什么会发生这种情况吗?

public interface EnumInf{
    public String toString();
    public int getIndex();
    public <T> T getEnum(int index);
}

public enum ENUM_A implements EnumInf{
    E_ZERO(0, "zero"),
    E_ONE(1, "one"),
    E_TWO(2, "two");

private int index;
private String name;
private ENUM_A(int _index, String _name){
    this.index = _index;
    this.name = _name;
}
public int getIndex(){
    return index;
}
public String toString(){
    return name;
}
// warning on the return type:
// Type safety:The return type ENUM_A for getEnum(int) from the type  ENUM_A needs unchecked conversion to conform to T from the type EnumInf
public ENUM_A getEnum(int index){
    return values()[index];
}

【问题讨论】:

  • 仅供参考,在界面中声明toString() 是没有用的。所有Objects 都已经声明了这一点。您需要做的就是在实现类中覆盖它。

标签: java generics enums


【解决方案1】:

试试这个:

public interface EnumInf<T extends EnumInf<T>> {
    public int getIndex();
    public T getEnum(int index);
}

public enum ENUM_A implements EnumInf<ENUM_A> {
    ... the rest of your code

(正如我在 cmets 中指出的,在界面中声明 toString() 是没有意义的。)

【讨论】:

  • 谢谢,你能解释一下它是如何消除警告的吗?
  • 我认为是因为在我的代码中,当你说ENUM_A implements EnumInf&lt;ENUM_A&gt;时,编译器可以在那里找出TENUM_A相同,所以方法的返回类型是相同。在您的原始代码中,显然它没有足够的信息来解决这个问题。也许这是因为实现方法的返回类型不必与接口方法相同,因为协方差。但我真的不确定。
  • 你使用的是原始类型
  • @newacct 请解释一下:(1)“你”是谁,(2)你指的原始类型是什么?
  • @newacct 好的,我进行了更改。也许这就是你所指的?我说不出来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多