Access to an enumeration value before defining it

If I had a listing

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

which would be the best way to store the value TUESDAYin the value MONDAY(for example, for use in the Days # nextDay method). I would think that I would MONDAY(TUESDAY)work, but I can not do this, because it TUESDAYis not yet defined. Is there a workaround for this (e.g. MONDAY(Days.valueOf("TUESDAY"))) or do I need to write a separate method?

Thank you in advance

+4
source share
4 answers

- , DayOfWeek, Java 8. 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-, 1- ..).
+6

abstract, . :

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

    abstract Days nextDay();
}
+2

You can also create a map:

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);
    }
}
+1
source
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;
    }
}

I do not know your purpose, but it works :-) Otherwise, you can use other answers.

0
source

All Articles