Shahid - 1 month ago 11x
Java Question

# Java days of week calculation

I have an Enum for Days of week (with Everyday, weekend and weekdays) as follows where each entry has an int value.

``````public enum DaysOfWeek {

Everyday(127),
Weekend(65),
Weekdays(62),
Monday(2),
Tuesday(4),
Wednesday(8),
Thursday(16),
Friday(32),
Saturday(64),
Sunday(1);

private int bitValue;

private DaysOfWeek(int n){
this.bitValue = n;
}

public int getBitValue(){
return this.bitValue;
}
}
``````

Given a TOTAL of any combination of the values, what would be the simplest way to calculate all individual values and make an arraylist from it. For example given the number 56 (i.e. Wed+Thur+Fri), how to calculate the days.

As Michael suggested do not expose this implementation detail to the outside world. Create a static method that converts int bitmask to EnumSet:

``````public static EnumSet< DaysOfWeek > fromBitValues (
)
{
final EnumSet< DaysOfWeek > ret_val =
EnumSet.noneOf( DaysOfWeek.class );

for ( final DaysOfWeek val : DaysOfWeek.values( ) )
{
if ( ( val.bitValue & bitMask ) == val.bitValue )
{

}
}

if ( bitMask != 0 )
{
throw
new IllegalArgumentException(
String.format(
"Bit mask value 0x%X(%d) has unsupported bits " +
"0x%X.  Extracted values: %s",
ret_val
)
);
}

return ret_val;
}
``````

You may also need a static method that converts an EnumSet to a bit mask, I leave this exercise to the reader.

Also, looking at your enum, Everyday, Weekends and Weekdays do not belong there. They are aggregates of you other DaysOfWeek values and as such should be defined as EnumSets.

Source (Stackoverflow)