Java - 每个枚举值的真/假
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24769742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - True/False per Enum value
提问by user3590149
I'm trying to figure out what is the best solution for my problem.
我试图找出解决我的问题的最佳方法。
I have an object where the status may be one of three possibilities but it can change during run time. I have three status flags that the object can be.
我有一个对象,其状态可能是三种可能性之一,但它可以在运行时更改。我有对象可以是的三个状态标志。
I have no experience with ENUM
and trying to figure out if this is the best way.
我没有经验ENUM
并试图弄清楚这是否是最好的方法。
I want to be able to set a specific flag to true
or false
and then be able to set another one. I need to be able to get the status of each flag as well for when I iterate through a list of these objects within a array list.
我希望能够将特定标志设置为true
orfalse
然后能够设置另一个标志。当我遍历数组列表中这些对象的列表时,我还需要能够获取每个标志的状态。
class Patient
{
//REST OF the object
public enum Status
{
INPATIENT(false),
OUTPATIENT(false),
EMERGENCY(false);
private final boolean isStatus;
Status(boolean isStatus)
{
this.isStatus = isStatus;
}
public boolean isStatus()
{
return this.isStatus;
}
}
}
采纳答案by Tobb
That's not really how an enum
works. You wouldn't include the boolean
flag, but instead do this:
这不是真正的enum
工作方式。你不会包括boolean
flag,而是这样做:
public enum Status {
INPATIENT,
OUTPATIENT,
EMERGENCY;
}
public class Patient {
private Status status;
public void setStatus(final Status status) {
this.status = status;
}
}
public class SomeService {
public void someMethod(final Patient patient) {
patient.setStatus(Status.INPATIENT);
patient.setStatus(Status.OUTPATIENT);
patient.setStatus(Status.EMERGENCY);
}
}
A variable typed as an enum
can hold any one value of that enum
(or null
). If you want to change status, change which value of the enum the variable refers to. (Enum
s are different from class
es, since they are not instantiated with the new
keyword, but rather just referenced directly, as in the above code.)
类型为 an 的变量enum
可以保存那个enum
(或null
)的任何一个值。如果要更改状态,请更改变量引用的枚举值。(Enum
s 与class
es不同,因为它们不是用new
关键字实例化的,而是直接引用的,如上面的代码。)
回答by PM 77-1
public enum StatusFlag { OUTPATEINT, INPATIENT, EMERGENCY}
public class Patient {
private StatusFlag status;
// Here goes more code
}
This will ensure that it would be impossible to assign any other values to status
field.
这将确保不可能为status
字段分配任何其他值。