java中的枚举

Enum was introduced in Java 1.5 as a new type whose fields consists of a fixed set of constants. For example, we can create directions as Java Enum with fixed fields as EAST, WEST, NORTH, and SOUTH.

Enum在Java 1.5中作为一种新类型引入,其字段由一组固定的常量组成。 例如,我们可以创建带有Java Enum的路线,并带有固定字段EAST,WEST,NORTH和SOUTH。

Java枚举 (Java Enum)

In this tutorial, we will learn know how to create an Enum. We will also look into the benefits of using enums in java and features of enum types. We will also learn using Java Enum valueOf, enum values, EnumSet and EnumMap with examples.

在本教程中,我们将学习如何创建枚举。 我们还将探讨在Java中使用枚举的好处以及枚举类型的功能。 我们还将学习将Java Enum valueOf ,枚举valuesEnumSetEnumMap与示例一起使用。

Java枚举示例 (Java Enum Example)

Java enum keyword is used to create an enum type. Let’s have a look at the java enum example program.

Java enum关键字用于创建枚举类型。 让我们看一下Java枚举示例程序。

package com.journaldev.enums;public enum ThreadStates {START,RUNNING,WAITING,DEAD;
}

In above example, ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING and DEAD.

在上面的示例中,ThreadStates是具有固定常量字段START,RUNNING,WAITING和DEAD的枚举。

Java枚举与常量 (Java Enum vs Constants)

Now let’s see how java enum is better than normal constants fields in Java classes.

现在让我们看一下Java枚举比Java类中的普通常量字段更好。

Let’s create a similar constants class in java.

让我们在java中创建一个类似的常量类。

package com.journaldev.enums;public class ThreadStatesConstant {public static final int START = 1;public static final int WAITING = 2;public static final int RUNNING = 3;public static final int DEAD = 4;
}

Now let’s see how both enum and constants are used in a java program:

现在,让我们看看如何在Java程序中同时使用枚举和常量:

/**
* This method shows the benefit of using Enum over Constants
*/
private static void benefitsOfEnumOverConstants() {//Enum values are fixedsimpleEnumExample(ThreadStates.START);simpleEnumExample(ThreadStates.WAITING);simpleEnumExample(ThreadStates.RUNNING);simpleEnumExample(ThreadStates.DEAD);simpleEnumExample(null);simpleConstantsExample(1);simpleConstantsExample(2);simpleConstantsExample(3);simpleConstantsExample(4);//we can pass any int constantsimpleConstantsExample(5);
}private static void simpleEnumExample(ThreadStates th) {if(th == ThreadStates.START) System.out.println("Thread started");else if (th == ThreadStates.WAITING) System.out.println("Thread is waiting");else if (th == ThreadStates.RUNNING) System.out.println("Thread is running");else System.out.println("Thread is dead");
}private static void simpleConstantsExample(int i) {if(i == ThreadStatesConstant.START) System.out.println("Thread started");else if (i == ThreadStatesConstant.WAITING) System.out.println("Thread is waiting");else if (i == ThreadStatesConstant.RUNNING) System.out.println("Thread is running");else System.out.println("Thread is dead");
}

If we look at the above example, we have two risks with using constants that are solved by the enum.

如果我们看上面的例子,使用由枚举解决的常量有两个风险。

  1. We can pass any int constant to the simpleConstantsExample method but we can pass only fixed values to simpleEnumExample, so it provides type safety.我们可以将任何int常量传递给simpleConstantsExample方法,但是我们只能将固定值传递给simpleEnumExample,因此它提供了类型安全性。
  2. We can change the int constants value in ThreadStatesConstant class but the above program will not throw any exception. Our program might not work as expected but if we change the enum constants, we will get compile time error that removes any possibility of runtime issues.我们可以在ThreadStatesConstant类中更改int常量值,但以上程序不会引发任何异常。 我们的程序可能无法按预期运行,但是如果我们更改枚举常量,则会出现编译时错误,从而消除了任何运行时问题。

Java枚举方法 (Java Enum Methods)

Now let’s see more features of java enum with an example.

现在,让我们看一个示例的Java枚举的更多功能。

package com.journaldev.enums;import java.io.Closeable;
import java.io.IOException;/*** This Enum example shows all the things we can do with Enum types**/
public enum ThreadStatesEnum implements Closeable{START(1){@Overridepublic String toString(){return "START implementation. Priority="+getPriority();}@Overridepublic String getDetail() {return "START";}},RUNNING(2){@Overridepublic String getDetail() {return "RUNNING";}},WAITING(3){@Overridepublic String getDetail() {return "WAITING";}},DEAD(4){@Overridepublic String getDetail() {return "DEAD";}};private int priority;public abstract String getDetail();//Enum constructors should always be private.private ThreadStatesEnum(int i){priority = i;}//Enum can have methodspublic int getPriority(){return this.priority;}public void setPriority(int p){this.priority = p;}//Enum can override functions@Overridepublic String toString(){return "Default ThreadStatesConstructors implementation. Priority="+getPriority();}@Overridepublic void close() throws IOException {System.out.println("Close of Enum");}
}

Java枚举要点 (Java Enum Important Points)

Below are some of the important points for Enums in Java.

以下是Java枚举中的一些要点。

  1. All java enum implicitly extends java.lang.Enum class that extends Object class and implements Serializable and Comparable interfaces. So we can’t extend any class in enum.所有java枚举都隐式扩展java.lang.Enum类,该类扩展了Object类并实现了Serializable和Comparable接口。 因此,我们无法在枚举中扩展任何类。
  2. Since enum is a keyword, we can’t end package name with it, for example com.journaldev.enum is not a valid package name.由于enum是关键字,因此我们不能使用它来结束软件包名称,例如com.journaldev.enum不是有效的软件包名称。
  3. Enum can implement interfaces. As in above enum example, it’s implementing Closeable interface.枚举可以实现接口 。 如上例所示,它实现了Closeable接口。
  4. Enum constructors are always private.枚举构造函数始终是私有的。
  5. We can’t create instance of enum using new operator.我们无法使用new运算符创建enum实例。
  6. We can declare abstract methods in java enum, then all the enum fields must implement the abstract method. In above example getDetail() is the abstract method and all the enum fields have implemented it.我们可以在Java枚举中声明抽象方法 ,然后所有枚举字段都必须实现抽象方法。 在上面的示例中, getDetail()是抽象方法,所有枚举字段都已实现了该方法。
  7. We can define a method in enum and enum fields can override them too. For example, toString() method is defined in enum and enum field START has overridden it.我们可以在枚举中定义一个方法,枚举字段也可以覆盖它们。 例如,在枚举中定义了toString()方法,枚举字段START已覆盖它。
  8. Java enum fields has namespace, we can use enum field only with class name like ThreadStates.STARTJava枚举字段具有名称空间,我们只能将枚举字段与类名一起使用,例如ThreadStates.START
  9. Enums can be used in switch statement, we will see it in action in the later part of this tutorial.枚举可以在switch语句中使用 ,我们将在本教程的后面部分中看到它的作用。
  10. We can extend existing enum without breaking any existing functionality. For example, we can add a new field NEW in ThreadStates enum without impacting any existing functionality.我们可以扩展现有的枚举而不破坏任何现有的功能。 例如,我们可以在ThreadStates枚举中添加一个新字段NEW而不影响任何现有功能。
  11. Since enum fields are constants, java best practice is to write them in block letters and underscore for spaces. For example EAST, WEST, EAST_DIRECTION etc.由于枚举字段是常量,因此Java最佳实践是使用大写字母并将其下划线表示空格。 例如EAST,WEST,EAST_DIRECTION等。
  12. Enum constants are implicitly static and final枚举常量是隐式静态的和最终的
  13. Enum constants are final but it’s variable can still be changed. For example, we can use setPriority() method to change the priority of enum constants. We will see it in usage in below example.枚举常量是最终的,但它的变量仍可以更改。 例如,我们可以使用setPriority()方法更改枚举常量的优先级。 我们将在下面的示例中看到它的用法。
  14. Since enum constants are final, we can safely compare them using “==” and equals() methods. Both will have the same result.由于枚举常量是最终常量,因此我们可以使用“ ==”和equals()方法安全地比较它们。 两者将具有相同的结果。

Java EnumSet,EnumMap,valueOf() (Java EnumSet, EnumMap, valueOf())

Now we know most of the features of Enum, let’s have a look at Java Enum example program. Then we will learn some more features of an enum.

现在我们知道了Enum的大多数功能,让我们看一下Java Enum示例程序。 然后,我们将学习枚举的更多功能。

package com.journaldev.enums;import java.io.IOException;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Set;public class JavaEnumExamples {public static void main(String[] args) throws IOException {usingEnumMethods();usingEnumValueOf();usingEnumValues();usingEnumInSwitch(ThreadStatesEnum.START);usingEnumInSwitch(ThreadStatesEnum.DEAD);usingEnumMap();usingEnumSet();}private static void usingEnumSet() {EnumSet enumSet = EnumSet.allOf(ThreadStatesEnum.class);for(ThreadStatesEnum tsenum : enumSet){System.out.println("Using EnumSet, priority = "+tsenum.getPriority());}}private static void usingEnumMap() {EnumMap<ThreadStatesEnum, String> enumMap = new EnumMap<ThreadStatesEnum,String>(ThreadStatesEnum.class);enumMap.put(ThreadStatesEnum.START, "Thread is started");enumMap.put(ThreadStatesEnum.RUNNING, "Thread is running");enumMap.put(ThreadStatesEnum.WAITING, "Thread is waiting");enumMap.put(ThreadStatesEnum.DEAD, "Thread is dead");Set keySet = enumMap.keySet();for(ThreadStatesEnum key : keySet){System.out.println("key="+key.toString()+":: value="+enumMap.get(key));}}private static void usingEnumInSwitch(ThreadStatesEnum th) {switch (th){case START:System.out.println("START thread");break;case WAITING:System.out.println("WAITING thread");break;case RUNNING:System.out.println("RUNNING thread");break;case DEAD:System.out.println("DEAD thread");}}private static void usingEnumValues() {ThreadStatesEnum[] thArray = ThreadStatesEnum.values();for(ThreadStatesEnum th : thArray){System.out.println(th.toString() + "::priority="+th.getPriority());}}private static void usingEnumValueOf() {ThreadStatesEnum th = Enum.valueOf(ThreadStatesEnum.class, "START");System.out.println("th priority="+th.getPriority());}private static void usingEnumMethods() throws IOException {ThreadStatesEnum thc = ThreadStatesEnum.DEAD;System.out.println("priority is:"+thc.getPriority());thc = ThreadStatesEnum.DEAD;System.out.println("Using overriden method."+thc.toString());thc = ThreadStatesEnum.START;System.out.println("Using overriden method."+thc.toString());thc.setPriority(10);System.out.println("Enum Constant variable changed priority value="+thc.getPriority());thc.close();}}

Before explaining other important features of enum, let’s see the output of the above program.

在解释枚举的其他重要功能之前,让我们看一下上面程序的输出。

priority is:4
Using overriden method.Default ThreadStatesConstructors implementation. Priority=4
Using overriden method.START implementation. Priority=1
Enum Constant variable changed priority value=10
Close of Enum
th priority=10
START implementation. Priority=10::priority=10
Default ThreadStatesConstructors implementation. Priority=2::priority=2
Default ThreadStatesConstructors implementation. Priority=3::priority=3
Default ThreadStatesConstructors implementation. Priority=4::priority=4
START thread
DEAD thread
key=START:: value=Thread is started
key=RUNNING:: value=Thread is running
key=WAITING:: value=Thread is waiting
key=DEAD:: value=Thread is dead
Using EnumSet, priority = 10
Using EnumSet, priority = 2
Using EnumSet, priority = 3
Using EnumSet, priority = 4

重要事项 (Important Points)

  1. The usingEnumMethods() methods shows how to create an enum object and how we can use its methods. It’s also showing use of setPriority(int i) method to change the variable of enum.usingEnumMethods()方法显示了如何创建枚举对象以及如何使用其方法。 它还显示了使用setPriority(int i)方法来更改enum的变量。
  2. usingEnumValueOf() shows the usage of java.util.Enum valueOf(enumType, name) through which we can create an enum object from String. It throws IllegalArgumentException if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type. It also throws NullPointerException if any of the arguments are null.usingEnumValueOf()显示了java.util.Enum valueOf(enumType, name)的用法,通过它我们可以从String创建一个枚举对象。 如果指定的枚举类型不具有带有指定名称的常量,或者指定的类对象不表示枚举类型,则抛出IllegalArgumentException 。 如果任何参数为null,它也会引发NullPointerException
  3. usingEnumValues() method shows the usage of values() method that returns an array containing all of the values of the enum in the order they are declared. Note that this method is automatically generated by java compiler for every enum. You won’t find values() implementation in java.util.Enum class.usingEnumValues()方法显示的使用()方法返回包含所有在他们声明的顺序的枚举的值的阵列。 请注意,此方法由java编译器为每个枚举自动生成。 您不会在java.util.Enum类中找到values()实现。
  4. The usingEnumInSwitch() method shows how to use enum constants in switch case.usingEnumInSwitch()方法演示了如何在切换时使用枚举常量。
  5. usingEnumMap() method shows use of java.util.EnumMap, which is introduced in Java 1.5 Collections Framework. EnumMap is 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. We can’t use null as key for EnumMap and EnumMap is not synchronized.usingEnumMap()方法显示了Java 1.5 Collections Framework中引入的java.util.EnumMap的使用。 EnumMap是与枚举类型键一起使用的Map实现。 枚举映射中的所有键都必须来自创建映射时显式或隐式指定的单个枚举类型。 我们不能将null用作EnumMap的键,并且EnumMap不同步。
  6. usingEnumSet() method shows use of java.util.EnumSet, which is Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection<E> c), of(E first, E... rest) and complementOf(EnumSet<E> s).usingEnumSet()方法显示java.util.EnumSet的使用, usingEnumSet()是Set实现,用于枚举类型。 枚举集中的所有元素都必须来自创建集时明确或隐式指定的单个枚举类型。 EnumSet不同步,并且不允许使用null元素。 它还提供了一些有用的方法,例如copyOf(Collection<E> c)of(E first, E... rest)complementOf(EnumSet<E> s)
GitHub Repository.GitHub Repository中检出所有示例。

Reference: Oracle Doc

参考: Oracle文档

翻译自: https://www.journaldev.com/716/java-enum

java中的枚举

java中的枚举_Java中的枚举相关推荐

  1. java 枚举_Java中的枚举类型(Enum)详解

    文章前记 程序员工作久了便可能整日忙碌于"增删改查"中,迷失方向,毫无进步. 该公众号致力于分享软件开发相关的原创干货,助你完成从程序员到架构师的进阶之路! 努力!做一个NB的Co ...

  2. java什么是枚举_java中的枚举到底是什么鬼

    枚举是一种特殊的数据类型,之所以特殊是因为它既是一种类(class)类型却又比类型多了些特殊的约束,但是这些约束的存在也造就了枚举类型的简洁,安全性以及便捷性. 创建枚举类型要使用enum关键字,隐含 ...

  3. java 文件解析异常_java中异常的解析

    Java Exception: 1.Error 2.Runtime Exception 运行时异常 3.Exception 4.throw 用户自定义异常 异常类分两大类型:Error类代表了编译和系 ...

  4. java enum 长度限制_Java中的Enum的使用与分析

    示例: public enum EnumTest { FRANK("The given name of me"), LIU("The family name of me& ...

  5. java是什么意思_java中是什么意思?

    慕田峪7331174 Java是一种可以撰写跨平台应用程序的面向对象的程序设计语言.Java技术具有卓越的通用性.高效性.平台移植性和安全性,广泛应用于PC.数据中心.游戏控制台.科学超级计算机.移动 ...

  6. java常见检查异常_java中常见异常总汇,附解释

    Java Exception: 1.Error 2.Runtime Exception 运行时异常 3.Exception 4.throw 用户自定义异常 异常类分两大类型:Error类代表了编译和系 ...

  7. java gc回收机制_Java中的GC回收机制

    为什么要进行GC回收? 当我们新建一个对象时,系统就会为其分配一定的内存空间,而有时候新建的对象没有去使用时,不回收的话会极大浪费内存空间,造成系统效率低下. 什么时候进行GC回收? 1.当CPU空闲 ...

  8. java变量存储位置_java 中变量存储位置的区别

    [原文] 1.寄存器:最快的存储区, 由编译器根据需求进行分配,我们在程序中无法控制. 2. 栈:存放基本类型的变量数据和对象的引用,但对象本身不存放在栈中,而是存放在堆(new 出来的对象)或者常量 ...

  9. java可以多重继承吗_Java中的多重继承与组合vs继承

    java可以多重继承吗 有时我写了几篇有关Java继承,接口和组成的文章. 在这篇文章中,我们将研究多重继承,然后了解组成优于继承的好处. Java中的多重继承 多重继承是创建具有多个超类的单个类的能 ...

最新文章

  1. 获取运行端口监听的用户身份auth-owner
  2. Oracle11g EM界面乱码解决方法
  3. 【遗传优化BP网络】基于自适应遗传算法的BP神经网络的股票预测MATLAB仿真
  4. corspost请求失败_vue项目CORS跨域请求500错误,post请求变options请求
  5. 任务导向型对话系统——对话管理模型研究最新进展
  6. hive 小文件数据合并
  7. Adobe Acrobat Pro设置高亮快捷键
  8. 微软热门开源项目及代码库地址
  9. bootstrap 4 pull-right无效
  10. azure 使用_使用Azure Data Studio开始您的旅程
  11. MYSQL—— 启动MYSQL 57 报错“The service MYSQL57 failed the most recent........等”的问题解决方式!...
  12. ViT (Vision Transformer) ---- Transformer Model(1)
  13. ubnutu更换合适源(阿里源)
  14. R485集线器定协议有多少种能否抗干扰?
  15. MVC已过时,MOVE时代来临?
  16. 腾讯短网址怎么在线生成
  17. 对比灵敏度丨信噪比 - 开会用的全向麦克风应该怎么选?
  18. 简易的打折与累加计算器
  19. 纯html+css打造一款特殊的生日贺卡
  20. PE 格式详解与试验

热门文章

  1. 【新闻发布系统】项目文档
  2. metasploit联动beef启动
  3. 数据降维之多维缩放MDS(Multiple Dimensional Scaling)
  4. Swift3.0 在其它类获取Appdelegate单例的属性或则对象的值
  5. t-sql的执行顺序
  6. vivado中的OOC技术
  7. Dijkstra求最短路径例题
  8. 记录一次有意思的XSS过滤绕过
  9. Vimtutor中文版
  10. 大数据搭建各个子项目时配置文件技巧(适合CentOS和Ubuntu系统)(博主推荐)...