Java枚举问题
我有两个 Enum,如下所示:
enum Connector {
AND, OR, XOR;
}
enum Component {
ACTIVITY
}
现在,我在类 Event
中有一个名为 follower
的变量。此变量(follower
)可以(并且应该具有)来自上述两个 Enum
中的任何一个的值。
那么,我应该为 follower
变量提供什么数据类型?
I have two Enum
s as follows:
enum Connector {
AND, OR, XOR;
}
enum Component {
ACTIVITY
}
Now, I have a variable named follower
in a class Event
. This variable (follower
) can have (and should have) value from either of the above two Enum
s.
So, What datatype should I give to the follower
variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
声明
follower
字段的接口。并让两个枚举都实现该接口。
然后你可以声明你的字段:
或者
这比将字段声明为
Enum< 有几个明显的优势? extends Follower>
(我能想到的)。通过这种方式,您可以自由地向Follower
接口添加方法,而无需将来修改字段,而您无法控制Enum
类型,因此如果您决定如果Follower
需要一个方法,那么您必须在每个地方更改声明。您的场景可能永远不会出现这种情况,但使用这种方式的成本很低,这是很好的防御实践。第二个稍微不太重要的优点,更多的是关于品味:它避免了类型中的泛型,当您包含通配符时,泛型可能会变得不太可读。
Declare an interface for the
follower
field.And have both the enums implement that interface.
Then you can declare your field:
Or
This has a couple distinct advantage over declaring the field as an
Enum<? extends Follower>
(that I can think of). With this way you are free to add methods to theFollower
interface without having to modify fields in the future, whereas you have no control over theEnum
type, so if you decided thatFollower
s needed a method, you would have to change the declaration in every place. This may never be the case with your scenario, but with so little cost to use this way, it's good defensive practice.A second, slightly less important advantage, which is more about taste: it avoids the generics in the type which, when you include wildcards, can become less readable.
你可以让两个枚举实现相同的接口,例如
Follower
,并让字段为:但你最好重新设计整个事情,这样感觉不太对劲。
And you can make both enums implement the same interface, for example
Follower
, and let the field be:But you'd better redesign the whole thing, it doesn't feel right this way.
您可以使用两个枚举的接口:
You can use an interface for both enums:
我建议创建一个名为 Follower 的新类。即使可能,我也不确定单个变量是否应该有两种不同的类型。
我倾向于将枚举视为原始数据类型,而您的问题就像问如何使变量成为 int 或 long 。
I would suggest creating a new Class called Follower. I'm not sure a single variable should have two different types even if it's possible.
I tend to think of Enums as primitive data types and your question would be like asking how do I make a variable be either int or long.
为什么不拥有 java.lang.Enum 类型的追随者。它是 java 中所有枚举的父级。
所以下面的代码工作得很好。
包 com.test;
枚举 NewEnum {
一、二;
}
枚举另一个{
三、四;
}
公共类 TestMe {
<代码>}
Why not to have follower of type java.lang.Enum. It is parent of all enums in java.
So following code works just fine.
package com.test;
enum NewEnum {
one, two;
}
enum Another {
three, four;
}
public class TestMe {
}