在定义之前访问枚举值

Accessing an enum value before it's defined

如果我有枚举

public enum Days {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

将值 TUESDAY 保存在值 MONDAY 中的最佳方法是什么(例如在方法 Days#nextDay 中使用)。我原以为 MONDAY(TUESDAY) 会起作用,但我不能这样做,因为 TUESDAY 尚未定义。是否有解决此问题的方法(例如 MONDAY(Days.valueOf("TUESDAY")))或我是否需要编写单独的方法?

提前致谢

我建议创建一个 abstract 方法,它在所有常量中实现。 return 值将是 第二天 :

public enum Days {
    MONDAY() {
        public Days nextDay() {
            return TUESDAY;
        }
    };
    //TODO: Implement the other days accordingly.

    abstract Days nextDay();
}

最简单和首选的方法是使用标准 类 方法之一,例如 DayOfWeek introduced in Java 8. You could simply use its plus(days) 方法移动到接下来的日子,例如

DayOfWeek foo = DayOfWeek.MONDAY.plus(1);//TUESDAY
DayOfWeek bar = DayOfWeek.SUNDAY.plus(1);//MONDAY 

但如果您的真正问题是关于其他一些枚举,您可以通过几种方式解决它。


其中一种方法是让每个 Enum 实例存储其 next 实例。我们可以在静态块中设置它们的值,在所有枚举值都已经声明之后:

enum Days {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

    static{
        MONDAY.next = TUESDAY;
        TUESDAY.next = WEDNESDAY;
        WEDNESDAY.next = THURSDAY;
        THURSDAY.next = FRIDAY;
        FRIDAY.next = SATURDAY;
        SATURDAY.next = SUNDAY;
        SUNDAY.next = MONDAY;
    }

    private Days next;

    public Days nextDay() {
        return next;
    }

}

MONDAY.nextDay() 将 return TUESDAY.


其他方法可以简单地添加方法,该方法将使用当前枚举的位置来获取下一个元素:

enum Days {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

    private static final Days[] VALUES = Days.values(); // store result of values()
                                                        // to avoid creating new array
                                                        // each time we use values()
    public Days nextDay() {
        return VALUES[(ordinal() + 1) % 7];
    }

}
  • values() returns 当前枚举中所有值的数组,按声明顺序排列
  • ordinal() returns 从 0 开始索引的当前枚举的位置(0-星期一,1-星期二,依此类推)。

您还可以构建地图:

public enum Days {
    MONDAY, TUESDAY;

    private static final Map<Days, Days> NEXT = new HashMap<>();

    static {
        NEXT.put(MONDAY, TUESDAY);
    }

    public static void main(String[] args) {
        final Days tuesday = Days.NEXT.get(MONDAY);
    }
}
public enum Days {
    MONDAY("Tuesday"), TUESDAY("Wednesday"), WEDNESDAY("Thursday"), THURSDAY(
            "Friday"), FRIDAY("Saturday"), SATURDAY("Sunday"), SUNDAY(
            "Monday");

    private String day;

    private Days(String day) {
        this.day = day;
    }

    public String getDay(){
        return day;
    }
}

我不知道你的目的,但这行得通:-)否则你可以使用其他答案。