开发者

How to store more than one option in a variable - Java

In Java, how would I create a property/field/variable that can at any one time store a couple of options/values, similar to lower level environments where you can set bits in variables, each meaning different things. I know that one can do this in Java by using static finals or something and then just ORing them all together, but isn't there a more elegant solution? E.g in C#开发者_如何学Python where you can have the [Flags] attribute to an Enum and then OR the states/values together into an instance of that Enum.

Any ideas?

Renault


Well, you can use an enum and then have an EnumSet for that enum. It's hard to know exactly what to recommend without more information. EnumSet is a good choice when you're naturally dealing with just "options" - but if you have multiple values (e.g. height and width; a fixed number of values which just naturally come together) then I'd just create a new type to encapsulate them.

If you could give concrete examples of what you're looking for, we may be able to help more.


The old-fashioned way (that you can still find in many libraries) would be to encode a bit mask using either an int value or a BitSet, but since JDK 1.5, an EnumSet is the preferred way to do it, as Jon Skeet says.


You mean like a C++ union? This is not allowed in Java because you lose type safety; this would allow you to get a reference to an Integer typed as a String, for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜