我想用泛型和枚舉設計一段代碼。我希望使用原始整數來獲得枚舉,並且它必須包含一個字符串。我有很多枚舉,所以我通過一個接口實現它們,以便記住覆蓋公共方法toString()
,getIndex()
和getEnum()
。然而,我正在得到一個類型安全警告,任何想法如何擺脫它,以及爲什麼發生?結合Java枚舉和泛型
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()'在界面也沒用。所有的'對象'已經聲明。你所需要做的就是在實現類中覆蓋它。 – ajb