Java 一周中的天数计算
我有一个一周中的天数(每天、周末和工作日)的枚举,如下所示,其中每个条目都有一个 int 值。
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;
}
}
给定值的任意组合的总计,计算所有单个值并从中创建数组列表的最简单方法是什么。例如给定数字 56(即周三+周四+周五),如何计算天数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
表示枚举值集合的正确方法是使用
EnumSet
。这在内部使用了位向量。但是在代码中暴露这样的实现细节并不是一个好主意。我们在这里进行面向对象,而不是闲聊。此外,您还混合了单个值和值集合的概念,这可能会导致以后出现麻烦。
使用
DayOfWeek
< 的示例/a> 枚举内置于 Java 8 及更高版本中。The correct way to represent a collection of enum values is to use an
EnumSet
. This uses a bit vector internally. But exposing such an implementation detail as in your code is not a good idea. We're doing OO here, not bit-twiddling.Additionally, you are mixing the concepts of a single value and a collection of values, which will likely lead to headaches down the road.
Example using the
DayOfWeek
enum built into Java 8 and later.正如迈克尔建议的那样,不要向外界公开这个实现细节。
创建一个将 int 位掩码转换为 EnumSet 的静态方法:
您可能还需要一个将 EnumSet 转换为位掩码的静态方法,我将此练习留给读者。
另外,看看你的枚举,每天、周末和工作日不属于那里。它们是其他 DaysOfWeek 值的聚合,因此应定义为 EnumSets。
As Michael suggested do not expose this implementation detail to the outside world.
Create a static method that converts int bitmask to EnumSet:
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.