Question

Here's what I'm trying to do. I have a field that encompasses multiple days per week. (E.g. it can store MONDAY or MONDAY | TUESDAY, or WEDNESDAY | FRIDAY) - basically any combination.

To do this I used an enum with powers of 2, like this:

public enum DayOfWeek {
    Monday(1),
    Tuesday(2),
    Wednesday(4),
    Thursday(8),
    Friday(16),
    Saturday(32),
    Sunday(64);

    private final int index;

    DayOfWeek(int index) {
        this.index = index;
    }

    public int value() {
        return index;
    }
}

Then I store an integer in the database like this:

DayOfWeek days = DayOfWeek.Monday | DayOfWeek.Thursday; // Monday and Thursday
int daysAsInt = (DayOfWeek)days; // Value to save

I can test the days as such

if ((days & DayOfWeek.Monday) == DayOfWeek.Monday) /* If days contains Monday */

My problem is I'm not sure how to get that integer value converted back to the DayOfWeek. I thought I could cast it (DayOfWeek)daysAsInt. But it doesn't work.

Any suggestions would be very appreciated.

Was it helpful?

Solution

Your enum is of individual days of the week - a variable of type DayOfWeek should only be expected to refer to a single day. If you're trying to store multiple values, you should look at an EnumSet:

EnumSet<DayOfWeek> days = EnumSet.of(DayOfWeek.Monday, DayOfWeek.Wednesday);
int valueToStore = setToValue(days);

Later:

int valueRetrieved = ...;
EnumSet<DayOfWeek> days = valueToSet(days);

where those methods are declared as:

static int setToValue(EnumSet<DayOfWeek> days) {
    int value = 0;
    for (DayOfWeek day : days) {
        value |= day.value();
    }
    return value;
}

static EnumSet<DayOfWeek> valueToSet(int value) {
    EnumSet<DayOfWeek> days = EnumSet.noneOf(DayOfWeek.class);
    for (DayOfWeek day : EnumSet.allOf(DayOfWeek.class)) {
        if ((value & day.value()) != 0) {
            days.add(day);
        }
    }
    return days;
}

OTHER TIPS

Since the integer could contain multiple days you can't just simply convert the integer back to a single DayOfWeek instance but you'd have to return an array/set/list of DayOfWeek elements.

To do this, you could provide a static method in DayOfWeek and check the int for each "index" (which isn't really an index but rather a flag/id).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top