Reputation:
I am trying to design a piece of code using generics and enums. I wish to get the enum using a primitive integer as well as it must hold a string. I have many enums, and so I implemented them with an interface so as to remember to override the public toString()
, getIndex()
and getEnum()
methods. However, I am getting a type safety warning, any idea how to get rid of it and why it is happening?
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];
}
Upvotes: 2
Views: 159
Reputation: 31689
Try this:
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
(As I noted in the comments, declaring toString()
in the interface is pointless.)
Upvotes: 4