为最后一个枚举值提供不同的变量值

Blr*_*lrp 0 java enums

我希望最后一个枚举在其中一个变量中具有不同的值:

private enum thing {
    thing0(0),
    thing1(1),
    thing2(2);

    int index;
    String s;

    private thing(int index) {
        this.index = index;
        s = index == values().length - 1 ? "b" : "a";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是行不通的;你不能values()在构造函数中调用。还有别的办法吗?

And*_*ner 5

一般来说,不要依赖枚举值的声明顺序。《Effective Java》第 3 版中的第 35 条“使用实例字段而不是序数”解释了原因。(请注意,当您使用 的实例字段时s,其值取决于序数。)

如果您希望特定值具有特定属性,请将其作为构造函数参数传递。

private enum thing {
    thing0(0),
    thing1(1),
    thing2(2, "b");

    int index;
    String s;

    private thing(int index) {
        this(index, "a");
    }

    private thing(int index, String s) {
        this.index = index;
        this.s = s;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您确实希望它检查枚举中的最后一个值,则另一种方法是使用 getter。将枚举中的静态最终字段初始化为最后一个值:

// Invokes `values()` twice, but meh, it's only executed once.
private static final thing LAST = values()[values().length-1];
Run Code Online (Sandbox Code Playgroud)

然后签入 getter:

String s() {
  return this == LAST ? "b" : "a";
}
Run Code Online (Sandbox Code Playgroud)