简体   繁体   中英

Combining Java Enum and Generics

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];
}

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM