简体   繁体   English

如何将具有分配值的枚举从C移植到Java?

[英]How to port enums with assigned values from C to Java?

I am trying to port a very simple app from C to Java. 我试图将一个非常简单的应用程序从C移植到Java。 Unfortunately I haven't worked quite a lot with enums before so the following code confuses me: 不幸的是,我之前在枚举方面工作不多,因此以下代码使我感到困惑:

typedef enum {
    LT = 0,
    LTE = 1,
    E = 2,
    GTE = 3,
    GT = 4
} S;

From my understanding the numbers are the values which represent every enum. 根据我的理解,数字是代表每个枚举的值。

How could I do the same in Java? 我该如何在Java中做同样的事情?

Should I take this approach 我应该采取这种方法吗

private enum S{
    LT,
    LTE,
    E,
    GTE,
    GT
}

or 要么

This approach? 这种方法?

private enum S{
    LT(0),
    LTE(1),
    E(2),
    GTE(3),
    GT(4);      

    private int code; 

    S(int code) {
        this.code = code;
    } 
    public int getCode() {
        return code;
    }
}

If the enumeration in Java already starts from 0 it would be a little redundant to add the second method. 如果Java中的枚举已经从0开始,那么添加第二种方法将有点多余。 I am confused... 我很困惑...

You should do it the first way. 您应该采用第一种方法。 The great thing about enum constants in Java is that they are not int values, so you do not need to assign values to them in this way. Java中的enum常量的伟大之处在于它们不是 int值,因此您无需以这种方式为其分配值。

If for some reason you need to know the index of an enum constant (and this is rare), you can do LT.ordinal() anyway. 如果出于某种原因您需要了解enum常量的索引(而且这种情况很少见),则可以执行LT.ordinal()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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