我是一名即将毕业的计算机科学专业的学生,在我的编码生涯中,我发现很少有使用枚举的实例,除了典型的情况,例如表示一副标准牌的面。
您知道在日常编码中使用枚举的任何巧妙方法吗?
为什么枚举如此重要?在什么情况下人们应该能够确定构建枚举是最好的方法?
I am an almost-graduating computer science student, and throughout my coding career, I've found very few instances where enumerations, except for canonical cases such as representing the faces of a standard deck of cards, are used.
Do you know of any clever ways that enums are used in everyday coding?
Why are enumerations so important and in what situations should one be able to identify that building an enumeration is the best approach?
发布评论
评论(7)
这些是
enum 的主要参数
,EnumMap
和 < code>EnumSet 通过简短的示例。enum
的情况从 Java 6 开始,
java.util.Calendar
是一个混乱的类的示例,它可以从使用enum
(以及其他改进)中受益匪浅。目前
Calendar
定义了以下常量 (还有许多其他):这些都是
int
,尽管它们显然代表不同的概念实体。以下是一些严重的后果:
MONDAY = 0;
、SUNDAY = 0;
,则我们有MONDAY == SUNDAY
int
:setMonth(JANUARY)
,但我们也可以setMonth(THURSDAY)
或setMonth(42)
set(int,int,int,int,int,int)
(一个真正的方法!)确实如此!相比之下,我们可以有这样的东西:
现在我们永远不必担心
MONDAY == SUNDAY
(它永远不会发生!),因为Month
和>DayOfWeek
是不同的类型,setMonth(MONDAY)
无法编译。此外,这里还有一些前后代码:
这里我们做出了各种假设,例如 JANUARY + 1 == FEBRUARY 等。另一方面,enum< /code> 对应的内容更简洁,更具可读性,并且做出的假设更少(因此出现 bug 的机会更少):
实例字段的情况
在 Java 中,
enum
是一个class
它具有许多特殊属性,但仍然是一个类
,允许您在必要时定义实例方法和字段。考虑以下示例:
另一方面,使用
enum
您可以编写如下内容:实例方法的情况
考虑以下示例:
如前面的示例所示,
enum
Java 中可以有实例方法,但不仅如此,每个常量也可以有自己特定的@Override
。下面的代码显示了这一点:EnumMap
的情况这里引用了 Effective Java 第二版:
本质上,与以前一样,您可能会遇到这样的情况:
现在您可以拥有:
EnumSet 的情况例如
,在 C++ 中,经常使用两个
int
常量的幂来表示位集。这依赖于按位运算。示例可能如下所示:使用
enum
和EnumSet
,这可能如下所示:参考文献
另请参阅
enum
代替int
常量EnumSet< /code>
代替位域
EnumMap< /code>
而不是顺序索引
相关问题
ordinal()
,但是...These are the main arguments for
enum
,EnumMap
, andEnumSet
by short examples.The case for
enum
As of Java 6,
java.util.Calendar
is an example of a messy class that could've benefited a lot from usingenum
(among other improvements).Currently
Calendar
defines the following constants (among many others):These are all
int
, even though they obviously represent different conceptual entities.The following are some serious consequences:
MONDAY = 0;
,SUNDAY = 0;
, then we haveMONDAY == SUNDAY
int
:setMonth(JANUARY)
, but we can alsosetMonth(THURSDAY)
orsetMonth(42)
set(int,int,int,int,int,int)
(a real method!) does!By contrast, we could have something like this instead:
Now we never have to worry about
MONDAY == SUNDAY
(it can never happen!), and sinceMonth
andDayOfWeek
are different types,setMonth(MONDAY)
does not compile.Additionally, here are some before-and-after codes:
Here we're making all sorts of assumptions, e.g.
JANUARY + 1 == FEBRUARY
, etc. On the other hand, theenum
counterpart is both more concise, more readable, and makes less assumptions (and therefore less chance for bugs):The case for instance fields
In Java,
enum
is aclass
that has many special properties, but aclass
nonetheless, allowing you to define instance methods and fields if necessary.Consider the following example:
On the other hand, with
enum
you can write something like this:The case for instance methods
Consider the following example:
As shown in previous example,
enum
in Java can have instance methods, but not only that but each constant can have its own specific@Override
as well. This is shown in the following code:The case for
EnumMap
Here's a quote from Effective Java 2nd Edition:
Essentially where as before you may have something like this:
Now you can have:
The case for
EnumSet
Power of two
int
constants are often used e.g. in C++ to denote bit sets. This relies on bitwise operations. An example may look something like this:With
enum
andEnumSet
, this can look something like this:References
See also
enum
instead ofint
constantsEnumSet
instead of bit fieldsEnumMap
instead of ordinal indexingRelated questions
ordinal()
, however...EnumSet
!在 Java 1.5 之前,您定义为
String
/int
常量的内容,现在应该定义为枚举。例如,而不是:您现在拥有一个更安全且对开发人员更友好的:
同样适用于具有多个选项的任何内容,例如状态、街道类型(str.、boul.、rd.等)、用户访问级别(管理员、版主、普通用户)等。
检查 更多示例和解释请参阅。
What you would define as
String
/int
constants before Java 1.5, you should now define as enums. For example, instead of having:You now have a safer and more developer-friendly:
Same goes for anything that has more than one options, like statuses, street types (str., boul., rd., etc), user access levels (administrator, moderator, regular user), etc. etc.
Check this for more examples and explanations.
考虑一些简单的代码:
没有枚举:
看起来不错,对吧?除了 SetOptions() 首先需要选项 B,然后是选项 A。这将很好地通过编译器,但在运行时会向后设置选项。
现在,对于枚举:
现在我们犯了同样的错误,但这一次,由于枚举是不同的类型,因此错误被编译器捕获。
(注意:我并不是真正的 Java 程序员,所以请原谅一些小的语法错误)
Consider some simple code:
without enums:
That look fine, right? Except SetOptions() wants Option B first and then Option A. This will go through the compiler just fine, but when run, sets the options backwards.
Now, with enums:
Now we make the same error, but this time, since enums are different types, the mistake is caught by the compiler.
(NOTE: I'm not really a Java programmer, so please forgive minor syntax errors)
我认为你在谈论枚举,而不是枚举器。
枚举非常适合应用程序中可能使用“魔术字符串”或“魔术数字”的任何地方。
最容易理解其用途的领域是文件访问。每种文件访问模式(读、写、追加)都在枚举中表示。如果您使用“幻数”,您可能会得到如下所示的结果:
当您可以使用枚举更清楚、更简洁地表达意图时:
I think you're talking about Enumerations, not Enumerators.
Enumerations are a good fit for anywhere in your application where you might otherwise use "magic strings" or "magic numbers".
The easiest area to understand their use is in File Access. Each file access mode (Read, Write, Append) is represented in the Enumeration. If you were using "magic numbers", you might have something that looks like:
When you could express the intent much more clearly and succinctly using an Enumeration:
默认答案:所有 Java 开发人员都应该明确阅读Effective Java Second Edition。有一章是关于enum的
Default answer: all Java developer should definitively read Effective Java Second Edition. There is a chapter about enum
枚举非常适合表示某事物的状态/状况。我经常使用枚举,例如:
枚举和派生类之间始终需要取得平衡。举一个简单的例子,考虑一个
Cat
类。猫
有不同程度的敌意。因此,我们可以创建派生类HostileCat
、FriendlyCat
等。但是,也有不同类型的猫,Lions
、Tigers突然间,我们有了一大堆
Cat
对象。因此,另一种解决方案是在Cat
类中提供Hostility
枚举,这可以减少派生类的数量和整体复杂性。Enumerations are perfect for representing the state/status of something. I often use enums such as:
There's always a balance to be struck between enumerations and derived classes. To give a simple example of this, consider a
Cat
class.Cats
have different levels of hostility. So, we could make derived classesHostileCat
,FriendlyCat
, etc. However, there are also different types of cats,Lions
,Tigers
, etc. Suddenly, we have a whole bunch ofCat
Objects. So, an alternative solution is to provide aHostility
enumeration in theCat
class, which reduces the number of derived classes and overall complexity.正如 Manuel Selva 所建议的,阅读Effective Java Second Edition,但也要阅读单例部分。 使用枚举是获得干净的单例对象的最简单方法。
As Manuel Selva suggested, read Effective Java Second Edition, but also read the singleton section. Using enum is the easiest way to have a clean singleton object.