为什么使用常量而不是枚举?

发布于 2024-11-28 12:58:31 字数 89 浏览 2 评论 0原文

我在很多很多 Java 库中看到了很多可以轻松使用枚举的常量。即使在 Swing 中,也有很多代码使用常量而不是枚举。为什么?

使用枚举有什么缺点?

I've seen in lots and lots of Java libraries the use of lots of constants where enums could have easily been used. Even in Swing, there is a lot of code that uses constants instead of enums. Why?

What are the disadvantages to using enums?

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

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

发布评论

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

评论(4

静若繁花 2024-12-05 12:58:31

因为枚举是在 Java 5 中引入的,而这些库很早之前就已经编写好了。重构它们将破坏大量现有应用程序。

Because enums were introduced in Java 5, and those libraries have been written long before. Refactoring them would break a bazillion of existing applications.

起风了 2024-12-05 12:58:31
  • 有很多关于使用预枚举解决方案的文档。
  • 有很多开发人员是第一次使用 Java,并且有使用另一种语言的经验,其中使用常量是常态。
  • 许多库希望支持 Java 1.4 及更早版本。 Java 1.3 和 Java 1.3 1.4至今仍在使用。
  • 工作代码并没有仅仅为了使用枚举而被重写。

我发现我仍然告诉人们使用枚举作为单例,尽管它已经存在了 7 年了。 :P

什么时候会使用常量而不是枚举?当您有许多关联但不直接相关的常量时。

public static final int BUFFER_SIZE = 32 * 1024;
public static final String ERROR = "Error: ";
public static final char TAB = 't';
  • There is a lot of documentation of using pre-enum solutions.
  • There are lots of developers who are using Java for the first time and have experience with another language where using constants is the norm.
  • A lot of libraries wanted to support Java 1.4 and earlier. Java 1.3 & 1.4 are still used today.
  • Working code hasn't been re-written just to use enums.

I find I still telling people to use enum for a Singleton even though it has been around for 7 years now. :P

When would use use constants instead of enum? When you have many associated but not directly related constants.

public static final int BUFFER_SIZE = 32 * 1024;
public static final String ERROR = "Error: ";
public static final char TAB = 't';
椵侞 2024-12-05 12:58:31

java中的Enum是在Java 5中引入的,以前没有这些,Enum相当于java中的类。

Enums in java are introduced in Java 5, these were not there before and Enum is equivalent to a class in java.

忘年祭陌 2024-12-05 12:58:31

在 Java 1.5 之前,Java 中没有枚举,实现枚举模式最直接的方法是使用 const int。您可以在 枚举的 Java 教程部分。

Prior to Java 1.5, there was no enum in Java, and the most straight-forward way to implement the enum pattern was to use const ints. You can read more in the Java Tutorial section for enums.

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