在定义之前访问枚举值

时间:2015-02-03 11:03:40

标签: java enums

如果我有枚举

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

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

提前谢谢

4 个答案:

答案 0 :(得分:6)

最简单和首选的方法是使用Java 8中引入的标准类之一,例如DayOfWeek。您可以简单地使用其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()将返回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()按照声明的顺序从当前枚举中返回所有值的数组
  • ordinal()返回从0开始索引的当前枚举的位置(0-MONDAY,1-TUESDAY等)。

答案 1 :(得分:2)

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

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

    abstract Days nextDay();
}

答案 2 :(得分: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);
    }
}

答案 3 :(得分:0)

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

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