在我的聊天应用程序中,我有一个枚举:
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System
}
ContactRelationType值的一半是房间(公会,军官,学院,社区,系统)。 我需要知道价值空间与否。
我知道有三种方法可以做到:
第一个:
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System;
public boolean isRoom() {
return this == Guild ||
this == Officers ||
this == Academy ||
this == Community ||
this == System;
}
}
它看起来很难看,IDEA告诉我“过于复杂的布尔表达式”而且它是。
第二个:
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System;
public boolean isRoom() {
switch (this) {
case Guild:
case Officers:
case Academy:
case Community:
case System:
return true;
default:
return false;
}
}
它看起来也很难看。
第三个:
public enum ContactRelationType {
Friend(false),
Familiar(false),
Ignored(false),
Unknown(false),
Guild(true),
Officers(true),
Academy(true),
Community(true),
System(true);
private boolean room;
ContactRelationType(boolean room) {
this.room = room;
}
public boolean isRoom() {
return room;
}
}
但在这种情况下,我在所有枚举实例中都有boolean room
。
那么,什么解决方案更好,为什么?
答案 0 :(得分:5)
你使用布尔标志的解决方案是好的。只需添加一个默认构造函数:
ContactRelationType() {
this(false);
}
现在您不必为每个枚举成员写true
或false
;仅适用于那些不是“默认”的人:
public enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild(true),
Officers(true),
Academy(true),
Community(true),
System(true);
答案 1 :(得分:4)
你可能会使用EnumSet
。它们使用BitSet
等效项非常有效地实现。
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System;
public boolean isRoomRelation() {
return RoomContacts.contains(this);
}
}
static final Set<ContactRelationType> RoomContacts = EnumSet.of(
ContactRelationType.Guild,
ContactRelationType.Officers,
ContactRelationType.Academy,
ContactRelationType.Community,
ContactRelationType.System);