Java 中的枚举。好处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2077634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:18:17  来源:igfitidea点击:

Enum in Java. Advantages?

javaenums

提问by gameover

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

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

采纳答案by FRotthowe

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.

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

回答by duffymo

Enums are already a class in Java.

枚举已经是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.

如果你问为什么这更好,我会说更好的类型安全和添加其他属性的能力而不是仅仅序数值。

回答by Chii

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.

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

回答by kdgregory

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:

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

AddItem(HttpMethod.POST, ProductEntry.class),

回答by Hyman Leow

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

除了更好的类型安全之外,您还可以在枚举中定义自定义行为(请参阅Effective Java以获取一些好的示例)。

回答by sateesh

Making enum a reference type that can contain fixed set of constants has led to efficient Mapimplementation like EnumMapand Setimplementation like EnumSet(JDK classes).

使 enum 成为可以包含固定常量集的引用类型导致了高效的Map实现(如EnumMap)Set实现(如EnumSet(JDK 类))。

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 的 javadoc :
用于枚举类型键的专用 Map 实现。枚举映射中的所有键都必须来自创建映射时显式或隐式指定的单个枚举类型。枚举映射在内部表示为数组。这种表示非常紧凑和高效。

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

EnumMap 结合了 Map 的丰富性和类型安全性以及数组的速度(Effective Java)。

回答by BalusC

The only realadvantage is that it can be used in a switchstatement. All the other stuff an enum is capable of can just be done with plain vanilla class with a privateconstructor whose instances in turn are declared as public static finalfields 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.

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

But if I'm not mistaken, in C++ (or was it C#?) you can use a Stringin a switchstatement. 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.

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

回答by cletus

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.

Java 5 枚举起源于Joshua BlochEffective Java(第一版)中的类型安全枚举模式,以避免 C/C++/C# 中枚举的陷阱(它们只是隐蔽的 int 常量)以及在 Java 中使用 final静态 int 常量。

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

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

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 privatemethod readResolveto stop Java creating new instances on deserialization, which would break simple reference checking (ie using the ==operator instead of equals()).

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

So Java 5 enums offer these advantages over ints:

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

  • Type safety;
  • Java 5 enums can have behaviour and implement interfaces;
  • Java 5 enums have some extremely lightweight data structures like EnumSetand EnumMap.
  • 类型安全;
  • Java 5 枚举可以有行为并实现接口;
  • Java 5 枚举有一些非常轻量级的数据结构,比如EnumSetEnumMap

Java 5 enums over these advantages over just using classes:

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

  • 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.
  • 不易出错的样板(私有构造函数readResolve()等);
  • 语义正确性。你看到某个东西是一个枚举,你知道它只是代表一个值。你看到一个类,你不确定。也许某处有一个静态工厂方法,等等。Java 5 枚举更清楚地表明意图。

回答by helpermethod

You can use enums to effectively implement Singletons ^^:

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

public enum Elvis {
    INSTANCE
}

回答by multiplayer1080

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.

使用枚举的好处:可以创建一个对象以与枚举相同的方式工作。事实上,直到 5.0 版本才包含在 Java 语言中。但是,枚举使代码更具可读性,并为程序员错误提供了更少的空间。

OCA Java SE 7 Programmer I Study Guide

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