Java中的“枚举”有什么用?

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

What's the use of "enum" in Java?

javaenums

提问by ZimZim

So I looked into this "enum" type, and it kind of seems like a glorified array/ArrayList/Listto me. What exactly is the use of it?

所以,我看着这个“枚举”类型,并且它种好像一个华而不实的数组/ ArrayList/List给我。它的具体用途是什么?

采纳答案by user219882

Enum serves as a type of fixed number of constants and can be used at least for two things

枚举作为一种固定数量的常量,至少可以用于两件事

constant

持续的

public enum Month {
    JANUARY, FEBRUARY, ...
}

This is much better than creating a bunch of integer constants.

这比创建一堆整数常量要好得多。

creating a singleton

创建单例

public enum Singleton {
    INSTANCE

   // init
};

You can do quite interesting things with enums, look at here

你可以用枚举做一些非常有趣的事情,看看这里

Also look at the official documentation

也看官方文档

回答by Guillaume USE

an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).

Enum 是一种安全类型,因此您无法在运行时分配新值。此外,您可以在 switch 语句(如 int)中使用它。

回答by xea

Enums are the recommended wayto provide easy-to-remember names for a defined set of contants (optionally with some limited behaviour too).

枚举是为一组定义的常量提供易于记忆的名称的推荐方法(也可以选择具有一些有限的行为)。

You should use enums where otherwise you would use multiple static integer constants (eg. public static int ROLE_ADMIN = 0or BLOOD_TYPE_AB = 2)

您应该使用枚举,否则您将使用多个静态整数常量(例如public static int ROLE_ADMIN = 0BLOOD_TYPE_AB = 2

The main advantages of using enums instead of these are type safety, compile type warnings/errors when trying to use wrong values and providing a namespace for related "constants". Additionally they are easier to use within an IDE since it helps code completion too.

使用枚举而不是这些的主要优点是类型安全、尝试使用错误值时编译类型警告/错误以及为相关的“常量”提供命名空间。此外,它们在 IDE 中更易于使用,因为它也有助于代码完成。

回答by Ashraf Bashir

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

枚举类型是其字段由一组固定常量组成的类型。常见示例包括罗盘方向(北、南、东和西的值)和一周中的几天。

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

任何时候需要表示一组固定的常量时,都应该使用枚举类型。这包括自然枚举类型,例如我们太阳系中的行星和数据集,其中您在编译时知道所有可能的值——例如,菜单上的选择、命令行标志等。

Here is some code that shows you how to use the Day enum defined above:

下面是一些代码,向您展示如何使用上面定义的 Day 枚举:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;

            case FRIDAY:
                System.out.println("Fridays are better.");
                break;

            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;

            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

The output is:

输出是:

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

星期一很糟糕。
周中的日子马马虎虎。
周五更好。
周末最好。
周末最好。

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

Java 编程语言枚举类型比其他语言中的枚举类型强大得多。枚举声明定义了一个类(称为枚举类型)。枚举类主体可以包括方法和其他字段。编译器在创建枚举时会自动添加一些特殊方法。例如,它们有一个静态值方法,该方法返回一个数组,该数组包含按声明顺序排列的枚举的所有值。此方法通常与 for-each 构造结合使用,以迭代枚举类型的值。例如,下面来自 Planet 类示例的代码遍历太阳系中的所有行星。

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

除了它的属性和构造函数之外,Planet 还有一些方法可以让您检索每个行星上物体的表面重力和重量。这是一个示例程序,它计算您在地球上的重量(以任何单位表示)并计算并打印您在所有行星上的重量(以同一单位表示):

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

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

If you run Planet.class from the command line with an argument of 175, you get this output:

如果从命令行运行 Planet.class,参数为 175,则会得到以下输出:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

$ java Planet 175
你在水星上
的重量是 66.107583你在金星上
的重量是 158.374842你在地球上
的重量是 175.000000你在火星上
的重量是 66.279007你在木星上
的重量是 442.847567
你在 SA7595 上
的重量是 442.847567 N75959597是 199.207413

Source: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

来源:http: //docs.oracle.com/javase/tutorial/java/javaOO/enum.html

回答by aioobe

You use an enuminstead of a classif the class should have a fixed enumerable number of instances.

如果类应该具有固定的可枚举实例数,则使用 anenum而不是 a 。class

Examples:

例子:

  • DayOfWeek = 7 instances → enum
  • CardSuit    = 4 instances → enum
  • Singleton = 1 instance   → enum

  • Product      = variable number of instances → class
  • User            = variable number of instances → class
  • Date            = variable number of instances → class
  • DayOfWeek = 7 个实例 → enum
  • CardSuit    = 4 个实例 → enum
  • Singleton = 1 个实例 → enum

  • Product      = 可变数量的实例 → class
  • User            = 可变数量的实例 → class
  • Date            = 可变数量的实例 → class

回答by Kuldeep Jain

Java programming language enumsare far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems(Not typesafe, No namespace, Brittleness and Printed values are uninformative) that exists with following int Enum pattern which was used prior to java 5.0 :

Java 编程语言enums远比其他语言中的对应物强大得多,它们只不过是美化的整数。新的枚举声明定义了一个完整的类(称为枚举类型)。除了解决Not typesafe, No namespace, Brittleness and Printed values are uninformativejava 5.0 之前使用的以下 int Enum 模式存在的所有问题():

public static final int SEASON_WINTER = 0;

public static final int SEASON_WINTER = 0;

it also allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparableand Serializable, and the serial form is designed to withstand arbitrary changes in the enum type. You can also use Enum in switchcase.

它还允许您向枚举类型添加任意方法和字段,以实现任意接口等。枚举类型提供了所有 Object 方法的高质量实现。它们是Comparableand Serializable,并且串行形式旨在承受枚举类型的任意更改。您也可以使用 Enumswitch以防万一。

Read the full article on Java Enums http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.htmlfor more details.

阅读有关 Java Enums 的完整文章http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html了解更多详细信息。

回答by Rangi Lin

An enumerated type is basically a data type that lets you describe each member of a type in a more readable and reliable way.

枚举类型基本上是一种数据类型,可让您以更易读和更可靠的方式描述类型的每个成员。

Here is a simple example to explain why:

这是一个简单的例子来解释原因:

Assuming you are writing a method that has something to do with seasons:

假设您正在编写一个与季节有关的方法:

The int enum pattern

int 枚举模式

First, you declared some int static constants to represent each season.

首先,您声明了一些 int 静态常量来表示每个季节。

public static final int SPRING = 0;
public static final int SUMMER = 1;
public static final int FALL = 2;
public static final int WINTER = 2;

Then, you declared a method to print name of the season into the console.

然后,您声明了一个将季节名称打印到控制台的方法。

public void printSeason(int seasonCode) {
    String name = "";
    if (seasonCode == SPRING) {
        name = "Spring";
    }
    else if (seasonCode == SUMMER) {
        name = "Summer";
    }
    else if (seasonCode == FALL) {
        name = "Fall";
    }
    else if (seasonCode == WINTER) {
        name = "Winter";
    }
    System.out.println("It is " + name + " now!");
}

So, after that, you can print a season name like this.

因此,在那之后,您可以打印这样的季节名称。

printSeason(SPRING);
printSeason(WINTER);

This is a pretty common (but bad) way to do different things for different types of members in a class. However, since these code involves integers, so you can also call the method like this without any problems.

这是为类中不同类型的成员做不同事情的一种很常见(但很糟糕)的方法。但是,由于这些代码涉及整数,因此您也可以像这样调用方法而不会出现任何问题。

printSeason(0);
printSeason(1);

or even like this

甚至像这样

printSeason(x - y);
printSeason(10000);

The compiler will not complain because these method calls are valid, and your printSeasonmethod can still work.

编译器不会抱怨,因为这些方法调用是有效的,并且您的printSeason方法仍然可以工作。

But something is not right here. What does a season code of 10000supposed to mean? What if x - yresults in a negative number? When your method receives an input that has no meaning and is not supposed to be there, your program knows nothing about it.

但这里有些不对劲。10000应该是什么意思的季节代码?如果x - y结果为负数怎么办?当您的方法收到一个没有意义且不应该在那里的输入时,您的程序对此一无所知。

You can fix this problem, for example, by adding an additional check.

例如,您可以通过添加附加检查来解决此问题。

...
else if (seasonCode == WINTER) {
    name = "Winter";
}
else {
    throw new IllegalArgumentException();
}
System.out.println(name);

Now the program will throw a RunTimeExceptionwhen the season code is invalid. However, you still need to decide how you are going to handle the exception.

现在程序会RunTimeException在季节代码无效时抛出a 。但是,您仍然需要决定如何处理异常。

By the way, I am sure you noticed the code of FALLand WINTERare both 2, right?

顺便说一句,我相信你注意到了FALL和的代码WINTER都是2,对吧?

You should get the idea now. This pattern is brittle. It makes you write condition checks everywhere. If you're making a game, and you want to add an extra season into your imaginary world, this pattern will make you go though all the methods that do things by season, and in most case you will forget some of them.

你现在应该明白了。这种模式很脆弱。它使您可以在任何地方编写条件检查。如果你正在制作一款游戏,并且你想在你的想象世界中添加一个额外的季节,这种模式会让你通过所有按季节做事的方法,并且在大多数情况下你会忘记其中的一些。

You might think class inheritance is a good idea for this case. But we just need some of them and no more.

在这种情况下,您可能认为类继承是一个好主意。但我们只需要其中的一些,不再需要。

That's when enumcomes into play.

这就是enum发挥作用的时候。



Use enumtype

使用enum类型

In Java, enumtypes are classes that export one instance for each enumeration constant via a public static final field.

在 Java 中,enum类型是通过公共静态 final 字段为每个枚举常量导出一个实例的类。

Here you can declare four enumeration constants: SPRING, SUMMER, FALL, WINTER. Each has its own name.

在这里您可以声明四个枚举常量:SPRING, SUMMER, FALL, WINTER. 每个都有自己的name

public enum Season {
    SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter");

    private String name;

    Season(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Now, back to the method.

现在,回到方法。

public void printSeason(Season season) {
    System.out.println("It is " + season.getName() + " now!");
}

Instead of using int, you can now use Seasonas input. Instead of a condition check, you can tell Seasonto give you its name.

int您现在可以将其Season用作输入,而不是使用。你可以告诉Season给你它的名字,而不是条件检查。

This is how you use this method now:

这是您现在使用此方法的方式:

printSeason(Season.SPRING);
printSeason(Season.WINTER);
printSeason(Season.WHATEVER); <-- compile error

You will get a compile-time error when you use an incorrect input, and you're guaranteed to get a non-null singleton reference of Seasonas long as the program compiles.

当您使用不正确的输入时,您将收到编译时错误,并且Season只要程序编译,您就可以保证获得非空的单例引用。

When we need an additional season, we simply add another constant in Seasonand no more.

当我们需要一个额外的季节时,我们只需添加另一个常量即可Season

public enum Season {
    SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter"), 
    MYSEASON("My Season");

...


Whenever you need a fixed set of constants, enumcan be a good choice (but not always). It's a more readable, more reliable and more powerful solution.

每当您需要一组固定的常量时,enum都会是一个不错的选择(但并非总是如此)。这是一个更易读、更可靠和更强大的解决方案。

回答by Naveen AH

1) enum is a keyword in Object oriented method.

1) enum 是面向对象方法中的关键字。

2) It is used to write the code in a Single line, That's it not more than that.

2) 用于将代码写在一行中,仅此而已。

     public class NAME
     {
        public static final String THUNNE = "";
        public static final String SHAATA = ""; 
        public static final String THULLU = ""; 
     }

-------This can be replaced by--------

  enum NAME{THUNNE, SHAATA, THULLU}

3) Most of the developers do not use enum keyword, it is just a alternative method..

3) 大多数开发者不使用 enum 关键字,它只是一种替代方法..