java 在java中使用枚举有什么好处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13839542/
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-10-31 14:08:44  来源:igfitidea点击:

what is the advantage of using enum in java?

javaenums

提问by user1720500

I was going through the enums in Java. The same what an enum can do can be achieved by collections or an array of Strings or user-defined types. What is the main purpose of introducing enums in Java 5.

我正在浏览 Java 中的枚举。枚举可以做的事情可以通过集合或字符串数​​组或用户定义类型来实现。在 Java 5 中引入枚举的主要目的是什么?

Thanks, Sehensaa

谢谢,Sehensaa

回答by Subhrajyoti Majumder

Advantages -

好处 -

  • Set of Constant declaration
  • Restrict input parameter in method
  • Can be usable in switch-case
  • 常量声明集
  • 限制方法中的输入参数
  • 可用于开关盒

It is used for fields consist of a fixed set of constants.

它用于由一组固定常量组成的字段

Example is Thread.State

例子是 Thread.State

public enum State {
    NEW,
    RUNNABLE,
    WAITING,
    BLOCKED,
    ...
}

or private enum Alignment { LEFT, RIGHT };

或者 private enum Alignment { LEFT, RIGHT };

You can restrict input parameter using Enumlike-

您可以使用Enum类似限制输入参数-

String drawCellValue (int maxCellLnghth, String cellVal, Alignment align){}

Here in align parameter could be only Alignment.LEFTor Alignment.RIGHTwhich is restricted.

这里的 align 参数可以是唯一的Alignment.LEFTAlignment.RIGHT受限制的。

Example of switch-case with enum-

带有enum-的开关盒示例

String drawCellValue (int maxCellLnghth, String cellVal, Alignment align){
    switch (align) {
    case LEFT:...
    case RIGHT: ...
    }
    ...
}

回答by Sumit Singh

From understanding-enums-in-java

理解枚举中的java

  1. Type safety. You can declare a function argument, return type, class member or local variable to be a particular Enum type and the compiler will enforce type safety;
  2. Enums are basically classes. They can implement interfaces, have behaviour and so on.
  1. 类型安全。您可以将函数参数、返回类型、类成员或局部变量声明为特定的 Enum 类型,编译器将强制执行类型安全;
  2. 枚举基本上是类。他们可以实现接口,拥有行为等等。

From enum-in-java-advantages
You get free compile time checking of valid values. Using

enum-in-java-advantages
您可以获得有效值的免费编译时检查。使用

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

回答by robertboloc

one of it's uses was as a means to emulate a switchon Strings type variables as before Java 7 this was not allowed

它的用途之一是switch作为在 Java 7 之前模拟Strings 类型变量的一种方法,这是不允许的

回答by Puce

Have a look for the "type-safe enum pattern" (e.g. in the book "Effective Java" 1st edition, by Joshua Bloch). The Java "enum" construct is a language level support (syntactic sugar) for this design pattern.

看看“类型安全的枚举模式”(例如,在 Joshua Bloch 的“Effective Java”第一版一书中)。Java“枚举”构造是此设计模式的语言级别支持(语法糖)。