如何将枚举映射到整数隐式

时间:2017-07-06 20:22:24

标签: java android

我知道我没有使用正确的行话,但基本上我想在C ++中使用此代码并将其移植到Java

public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC, 
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1, 

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}

我想显式地将枚举映射到int,然后让每个后续的枚举隐式映射到该整数的下一个增量(或者尽可能接近这个C代码的某个解决方案)。

3 个答案:

答案 0 :(得分:3)

在Java中,您可以为Enum分配值,如果这是您要查找的内容。它看起来像这样:

public enum Packets {
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3);

    private int value;

    Packets(int value){
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

现在你可以像这样调用枚举来获得它的价值:

Packets.PACKET_SYNC.getValue(); //It will return 1

答案 1 :(得分:3)

您可以在枚举中添加一个字段,在枚举常量的构造函数调用中初始化此字段,然后从公共getter返回此字段。这应该是这样的:

public enum Packets
{
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(14),
    PACKET_FILLI(15),
    PACKET_GLASSI(16);

    private final int id;

    private MyEnum(final int id) {
        this.id = id;
    }

    public final int getId() {
        return index;
    }
}

答案 2 :(得分:2)

这不是一个简洁的解决方案,但是如果你真的想要自动初始化它们以与C ++声明相同的方式递增,而不是明确定义每个单独的ID,你可以这样做:

TypeDF <- read.table(text = TYPES, sep = ",", as.is = TRUE, col.names = "Type")
sqldf("select d.* 
       from df d 
       join TypeDF t on substr(d.Type, 1, instr(d.Type, '_') - 1) = t.Type")

然后你调用初始化,它将为你填写ID:

public enum Packets
{
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(),
    PACKET_FILLI(),
    PACKET_GLASSI();

    private int id;

    private Packets(int id) {
        this.id = id;
    }

    private Packets(){
        this.id = -1;
    }

    public final int getId() {
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public static void initIds(){
        for(Packets p : Packets.values()){
            if(p.getId()==-1){
                if(p.ordinal()==0){
                    p.setId(0);
                }else{
                    p.setId(Packets.values()[p.ordinal()-1].getId()+1);
                }
            }
        }
    }
}

编辑/添加

如果将代码从Packets.initIds(); System.out.println(Packets.PACKET_AVAIL_1.getId()); //3 System.out.println(Packets.PACKET_GLASS.getId()); //13 System.out.println(Packets.PACKET_FILL.getId()); //14 System.out.println(Packets.PACKET_FILLI.getId()); //15 方法移动到静态初始化程序块中,则不需要在代码中的某处进行初始化调用:

initIds()