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.
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 int valueToSet(int value) {
EnumSet<DayOfWeek> days = EnumSet.noneOf(EnumSet.class);
for (DayOfWeek day : EnumSet.allOf(EnumSet.class)) {
if ((value & day.value()) != 0) {
days.add(day);
}
}
return days;
}
See more on this question at Stackoverflow