与具有公共静态最终字段的类相比,Java 枚举的优势是什么? [英] What's the advantage of a Java enum versus a class with public static final fields?

查看:28
本文介绍了与具有公共静态最终字段的类相比,Java 枚举的优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常熟悉 C#,但开始更多地使用 Java.我希望了解到 Java 中的枚举基本上等同于 C# 中的枚举,但显然情况并非如此.最初我很高兴得知 Java 枚举可以包含多条数据,这似乎非常有利 (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html).但是,从那时起,我发现 C# 中缺少许多微不足道的功能,例如能够轻松地为枚举元素分配某个值,以及因此无需花费大量精力即可将整数转换为枚举的能力(即将整数值转换为匹配的Java Enum).

I am very familiar with C# but starting to work more in Java. I expected to learn that enums in Java were basically equivalent to those in C# but apparently this is not the case. Initially I was excited to learn that Java enums could contain multiple pieces of data which seems very advantageous (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). However, since then I have found a lot of features missing that are trivial in C#, such as the ability to easily assign an enum element a certain value, and consequently the ability to convert an integer to an enum without a decent amount of effort (i.e. Convert integer value to matching Java Enum).

所以我的问题是:Java 枚举比具有一堆公共静态最终字段的类有什么好处吗?或者它只是提供了更紧凑的语法?

So my question is this: is there any benefit to Java enums over a class with a bunch of public static final fields? Or does it just provide more compact syntax?

让我更清楚.Java 枚举相对于具有一堆相同类型的公共静态最终字段的类有什么好处?例如,在第一个链接的行星示例中,枚举与具有这些公共常量的类相比有什么优势:

Let me be more clear. What is the benefit of Java enums over a class with a bunch of public static final fields of the same type? For example, in the planets example at the first link, what is the advantage of an enum over a class with these public constants:

public static final Planet MERCURY = new Planet(3.303e+23, 2.4397e6);
public static final Planet VENUS = new Planet(4.869e+24, 6.0518e6);
public static final Planet EARTH = new Planet(5.976e+24, 6.37814e6);
public static final Planet MARS = new Planet(6.421e+23, 3.3972e6);
public static final Planet JUPITER = new Planet(1.9e+27, 7.1492e7);
public static final Planet SATURN = new Planet(5.688e+26, 6.0268e7);
public static final Planet URANUS = new Planet(8.686e+25, 2.5559e7);
public static final Planet NEPTUNE = new Planet(1.024e+26, 2.4746e7);

据我所知,casablanca 的答案是唯一满足这一点的答案.

As far as I can tell, casablanca's answer is the only one that satisfies this.

推荐答案

从技术上讲,确实可以将枚举视为具有一堆类型化常量的类,这实际上是枚举常量在内部实现的方式.但是,使用 enum 可为您提供有用的方法 (Enum javadoc) 否则您必须自己实现,例如 Enum.valueOf.

Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf.

这篇关于与具有公共静态最终字段的类相比,Java 枚举的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆