gpt4 book ai didi

java - 如何获取枚举值的附加属性?

转载 作者:行者123 更新时间:2023-12-03 02:02:26 26 4
gpt4 key购买 nike

在我的聊天应用程序中,我有一个枚举:

enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System
}

ContactRelationType 值的一半是房间(公会、军官、学院、社区、系统)。我需要知道是否有值(value)的房间。

我知道三种方法:

第一个:

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 告诉我“boolean 表达式过于复杂”,事实确实如此。

第二个:

    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 空间

那么,什么解决方案更好,为什么?

最佳答案

带有 boolean 标志的解决方案很好。只需添加一个默认构造函数:

 ContactRelationType() {
this(false);
}

现在您不必为每个枚举成员编写 truefalse;仅适用于那些非“默认”的:

public enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild(true),
Officers(true),
Academy(true),
Community(true),
System(true);

关于java - 如何获取枚举值的附加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com