每个枚举项目的编号? [英] Number for each enum item?
本文介绍了每个枚举项目的编号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以在java中定义这样的东西吗?
Is it possible to define something like this in java?
C#代码:
public enum Character
{
A = 1,
B = 2,
C = 4,
D = 8
}
...
Character ch = /* from user */
if(ch & Character.A)
{
// some operation...
}
例如,如果 ch
设置为 CharacterB
那么的结果如果
将是 false
:
for example if ch
set to Character.B
then result of if
will be false
:
ch = 00000000 00000000 00000000 00000010
A = 00000000 00000000 00000000 00000001
------------------------------------------
& 00000000 00000000 00000000 00000000
我想实现这样的东西!在Java中有可能吗?
I want to implement something like that! Is it ever possible in Java?
推荐答案
嗯,你可以几乎:
public enum CharEnum // Let's avoid java.lang.* clashes
{
A(1), B(2), C(4), D(8);
private final int mask;
private CharEnum(int mask)
{
this.mask = mask;
}
public int getMask()
{
return mask;
}
}
然后:
CharEnum ch = /* from user */
if ((ch.getMask() & CharEnum.A.getMask()) > 0)
{
// some operation...
}
这在某些情况下可能是有用的,但是迈克尔说你一定要看看 EnumSet
一般的一组值选项。
This can be useful in some situations, but as Michael said you should definitely look at EnumSet
for general "set of values" options.
如果您确定要使用枚举枚举值,则可以在枚举本身中添加额外的逻辑:
If you do decide to go for an enum with values, you can put extra logic within the enum itself:
public enum CharEnum
{
// Other code as before
public boolean overlapsWith(CharEnum ch)
{
return (ch.mask & mask) > 0;
}
}
这篇关于每个枚举项目的编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文