Java 中的枚举。优点?

发布于 2024-08-18 06:11:20 字数 46 浏览 4 评论 0原文

在 Java 中使枚举类似于类,而不是像 C/C++ 中的常量集合有哪些优点?

What are some advantages of making enum in Java similar to a class, rather than just a collection of constants as in C/C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

我早已燃尽 2024-08-25 06:11:20

您可以免费在编译时检查有效值。使用

public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;

并不确保

void selectOption(int option) {
...
}

只接受 0 或 1 作为参数值。使用枚举,这是有保证的。此外,这会导致更多的自记录代码,因为您可以使用代码完成来查看所有枚举值。

You get free compile time checking of valid values. Using

public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;

does not ensure

void selectOption(int option) {
...
}

will only accept 0 or 1 as a parameter value. Using an enum, that is guaranteed. Moreover, this leads to more self documenting code, because you can use code completion to see all enum values.

笑叹一世浮沉 2024-08-25 06:11:20

类型安全是原因之一。

另一个我发现更重要的是,您可以将元数据附加到Java 中的枚举值。例如,您可以使用枚举来定义 Web 服务的合法操作集,然后附加请求类型和数据类的元数据:

AddItem(HttpMethod.POST, ProductEntry.class),

Type safety is one reason.

Another, that I find more important, is that you can attach metadata to enum values in Java. For example, you could use an enum to define the set of legal operations for a webservice, and then attach metadata for the type of request and data class:

AddItem(HttpMethod.POST, ProductEntry.class),
ぇ气 2024-08-25 06:11:20

Java 5 枚举源自 Joshua BlochEffective Java(第一版)以避免 C/C++/C# 中枚举(它们只是简单的 int 常量)的陷阱以及 Java 中最终静态 int 常量的使用。

主要是 int 常量和 int 枚举不是类型安全的。您可以传入任何 int 值。在 C/C++ 中,您可以这样做:

enum A { one, two, three };
enum B { beef, chicken, pork } b = beef;

void func(A a) { ... }
func((A)b);

不幸的是,Effective Java 中的类型安全枚举模式有很多样板文件,但并非全部都是显而易见的。最值得注意的是,您必须重写 private 方法 readResolve 来阻止 Java 在反序列化时创建新实例,这会破坏简单的引用检查(即使用 == 运算符而不是 equals())。

因此,与 int 相比,Java 5 枚举具有以下优势:

  • 类型安全;
  • Java 5 枚举可以具有行为并实现接口;
  • Java 5 枚举有一些极其轻量级的数据结构,例如 EnumSetEnumMap

与仅使用类相比,Java 5 枚举具有以下优势:

  • 不易出错的样板文件(私有构造函数、readResolve() 等);
  • 语义正确性。您看到某个东西是一个枚举,并且您知道它只是代表一个值。你看到一堂课,但你不确定。也许某处有一个静态工厂方法,等等。Java 5 枚举更清楚地表明意图。

Java 5 enums originated from a typesafe enum pattern from Joshua Bloch's Effective Java (the first edition) to avoid the pitfalls of enums in C/C++/C# (which are simply thinly-veiled int constants) and the use in Java of final static int constants.

Primarily int constants and int enums aren't typesafe. You can pass in any int value. In C/C++ you can do this:

enum A { one, two, three };
enum B { beef, chicken, pork } b = beef;

void func(A a) { ... }
func((A)b);

Unfortunately the typesafe enum pattern from Effective Java had a lot of boilerplate, not all of it obvious. The most notable is you had to override the private method readResolve to stop Java creating new instances on deserialization, which would break simple reference checking (ie using the == operator instead of equals()).

So Java 5 enums offer these advantages over ints:

  • Type safety;
  • Java 5 enums can have behaviour and implement interfaces;
  • Java 5 enums have some extremely lightweight data structures like EnumSet and EnumMap.

Java 5 enums over these advantages over just using classes:

  • Less error-prone boilerplate (private constructor, readResolve() etc);
  • Semantic correctness. You see something is an enum and you know it's just representing a value. You see a class and you're not sure. Maybe there's a static factory method somewhere, etc. Java 5 enums much more clearly indicate intent.
轻拂→两袖风尘 2024-08-25 06:11:20

除了更好的类型安全性之外,您还可以在枚举中定义自定义行为(请参阅 Effective Java< /a> 一些很好的例子)。

In addition to better type safety, you can also define custom behavior in your enums (refer to Effective Java for some good examples).

本王不退位尔等都是臣 2024-08-25 06:11:20

枚举已经是 Java 中的类

如果您问为什么这更好,我会说更好的类型安全性以及除了单纯的序数值之外添加其他属性的能力。

Enums are already a class in Java.

If you're asking why this is better, I'd say that better type safety and the ability to add other attributes besides a mere ordinal value would come to mind.

握住我的手 2024-08-25 06:11:20

您可以使用枚举来有效地实现单例^^:

public enum Elvis {
    INSTANCE
}

You can use enums to effectively implement Singletons ^^:

public enum Elvis {
    INSTANCE
}
给我一枪 2024-08-25 06:11:20

将 enum 设为可以包含固定常量集的引用类型,可以实现高效的 Map 实现(如 EnumMap)和 Set 实现(如 EnumSet<) /i>(JDK 类)。

来自 EnumMap 的 javadoc :
<我>
与枚举类型键一起使用的专用 Map 实现。枚举映射中的所有键必须来自创建映射时显式或隐式指定的单个枚举类型。枚举映射在内部表示为数组。这种表示方式极其紧凑且高效。

EnumMap 将 Map 的丰富性和类型安全性与数组的速度结合起来(有效Java)。

Making enum a reference type that can contain fixed set of constants has led to efficient Map implementation like EnumMap and Set implementation like EnumSet (JDK classes).

From javadoc of EnumMap :

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

EnumMap combines richness and type safety of Map with the speed of an array (Effective Java).

甜尕妞 2024-08-25 06:11:20

枚举本身就是一种类型 - 您不能使用不存在的枚举,也不能放入其他类似的常量。并且还可以枚举它们,使代码更加简洁。

使用静态常量可能会导致维护噩梦 - 特别是当它们分散时。

Enums are a type in itself - you cannot use an enum that does not exist, or put in some other similar looking constant. and also, you can enumerate them, so that code can be more concise.

using static constants could potentially cause maintenence nightmares - especially if they area spread out.

扮仙女 2024-08-25 06:11:20

唯一真正的优点是它可以在 switch 语句。枚举能够完成的所有其他事情都可以使用带有 private 构造函数的普通普通类来完成,该构造函数的实例又被声明为该类的 public static final 字段问题(类型安全模式)。枚举的另一个优点显然是它使代码比普通类更简洁。

但如果我没记错的话,在 C++(或者是 C#?)中,您可以在 switch 语句中使用 String 。因此,与 C++ 相比,Java 中枚举的优势可以忽略不计。然而,Java 7 也提出了同样的建议,不确定它是否会成功。

The only real advantage is that it can be used in a switch statement. All the other stuff an enum is capable of can just be done with plain vanilla class with a private constructor whose instances in turn are declared as public static final fields of the class in question (the typesafe pattern). The other advantage of enum is obviously that it makes the code less verbose than you would do with a plain vanilla class.

But if I'm not mistaken, in C++ (or was it C#?) you can use a String in a switch statement. So that advantage of enums in Java is negligible as opposed to C++. However, same thing was proposed for Java 7, not sure if it will make it.

从﹋此江山别 2024-08-25 06:11:20

使用枚举的好处:
可以创建一个对象,使其以与枚举相同的方式工作。实际上,
直到 5.0 版本,枚举才被包含在 Java 语言中。然而,
枚举使代码更具可读性,并减少程序员出错的空间。

OCA Java SE 7 程序员 I 学习指南

Benefits of Using Enumerations:
An object can be created to work in the same manner as an enumeration. In fact,
enumerations were not even included in the Java language until version 5.0. However,
enumerations make code more readable and provide less room for programmer error.

OCA Java SE 7 Programmer I Study Guide

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文