Java Enums

Table of Contents

Java Enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. Java enums were added in Java 5.

Enum Example

Here is a simple Java enum example:

public enum Level {
    HIGH,
    MEDIUM,
    LOW
}

Notice the enum keyword which is used in place of class or interface. The Java enum keyword signals to the Java compiler that this type definition is an enum.

You can refer to the constants in the enum above like this:

Level level = Level.HIGH;

Notice how the level variable is of the type Level which is the Java enum type defined in the example above. The level variable can take one of the Level enum constants as value (HIGHMEDIUM or LOW). In this caselevel is set to HIGH.

Enums in if Statements

Since Java enums are constants you will often have to compare a variable pointing to an enum constant against the possible constants in the enum type. Here is an example of using a Java enum in an if-statement:

Level level = ...  //assign some Level constant to it

if( level == Level.HIGH) {

} else if( level == Level.MEDIUM) {

} else if( level == Level.LOW) {

}

This code compares the level variable against each of the possible enum constants in the Level enum.

If one of the enum values occur more often than the others, checking for that value in the first if-statement will result in better performance, as less comparison on average are executed. This is not a big difference though, unless the comparisons are executed a lot.

Enums in switch Statements

If your Java enum types contain a lot constants and you need to check a variable against the values as shown in the previous section, using a Java switch statement might be a good idea.

You can use enums in switch statements like this:

Level level = ...  //assign some Level constant to it

switch (level) {
    case HIGH   : ...; break;
    case MEDIUM : ...; break;
    case LOW    : ...; break;
}

Replace the ... with the code to execute if the level variable matches the given Level constant value. The code could be a simple Java operation, a method call etc.

Enum Iteration

You can obtain an array of all the possible values of a Java enum type by calling its static values() method. All enum types get a static values() method automatically by the Java compiler. Here is an example of iterating all values of an enum:

for (Level level : Level.values()) {
    System.out.println(level);
}

Running this Java code would print out all the enum values. Here is the output:

HIGH
MEDIUM
LOW

Notice how the names of the constants themselves are printed out. This is one area where Java enums are different than static final constants.

Enum Fields

You can add fields to a Java enum. Thus, each constant enum value gets these fields. The field values must be supplied to the constructor of the enum when defining the constants. Here is an example:

public enum Level {
    HIGH  (3),  //calls constructor with value 3
    MEDIUM(2),  //calls constructor with value 2
    LOW   (1)   //calls constructor with value 1
    ; // semicolon needed when fields / methods follow

    private final int levelCode;

    public Level(int levelCode) {
        this.levelCode = levelCode;
    }
}

Notice how the Java enum in the example above has a constructor which takes an int. The enum constructor sets the int field. When the constant enum values are defined, an int value is passed to the enum constructor.

Enum Methods

You can add methods to a Java enum too. Here is an example:

public enum Level {
    HIGH  (3),  //calls constructor with value 3
    MEDIUM(2),  //calls constructor with value 2
    LOW   (1)   //calls constructor with value 1
    ; // semicolon needed when fields / methods follow

    private final int levelCode;

    Level(int levelCode) {
        this.levelCode = levelCode;
    }
    
    public int getLevelCode() {
        return this.levelCode;
    }
    
}

You call an enum method via a reference to one of the constant values. Here is Java enum method call example:

Level level = Level.HIGH;

System.out.println(level.getLevelCode());

This code would print out the value 3 which is the value of the levelCode field for the enum constant HIGH.

You are not restricted to simple getter and setter methods. You can also create methods that make calculations based on the field values of the enum constant. If your fields are not declared final you can even modify the values of the fields (although that may not be so good an idea, considering that the enums are supposed to be constants).

Enum Miscellaneous Details

Java enums extend the java.lang.Enum class implicitly, so your enum types cannot extend another class.

If a Java enum contains fields and methods, the definition of fields and methods must always come after the list of constants in the enum. Additionally, the list of enum constants must be terminated by a semicolon;

时间: 2024-08-19 02:36:40

Java Enums的相关文章

java的奇技淫巧--意外行为与特性(译文)

Java是一种非常成熟的编程语言 - 事实上,它已经走过21年了,如果它是一个人,它可以在美国随便混!随着年龄的增长,智慧也在增长,而至少有时候,有些东西会变得很怪异.在本文中,我将介Java语言的一些奇技淫巧的行为和特征. 在这里,没有特别的顺序去介绍一系列Java的奇技淫巧,仅供娱乐,或者你向朋友们推介它吧. Java有goto和const关键字 虽然Java没有goto,但它确实作为保留关键字.const也是这样.这意味着您无法这两个名称定义变量: int goto = 0; int co

Java开发工具JetBrains IntelliJ IDEA 2019.2.1汉化版

IntelliJ IDEA mac 汉化版是一款功能强大,功能多样且用户友好的Java IDE,专门设计用于借助众多工具和功能提高您的工作效率.IntelliJ IDEA 2019提供了一套全面的功能,以及使用Java,Groovy,Scala和其他语言进行Web和企业开发的最先进技术和框架的工具和集成. 最重要的是,IntelliJ IDEA支持各种构建系统和单元测试框架集成以及直观的测试运行UI.您还可以享受JavaScript,HTML,CSS和其他语言和技术的简单编辑器,如LESS,Sa

中秋佳节--理解Enum枚举

一.Enum枚举的作用 1.使用枚举可以限定取值范围,枚举中定义的每个常量都可以理解为对象: Eg: Public enum Color{ RED, GREEN,BULE; } 说明:RED实际上就表示的是枚举的名称,默认的编号是0,可以使用ordinal()方法获得. 2.使用enum关键字定义枚举类,其中包含的对象可以初始化定义(初始化构造函数) Eg: package cn.test.java.enums; enum ColorDemo{ RED("红色"),GREEN(&quo

JI_4

(1) OOP and Design Patterns (1.1) Please explain difference among class, interface and abstract class. When you would use it rather than other? Feature Interface Abstract class Multiple inheritance A class may implement multiple interfaces. A class m

针对android方法数64k的限制,square做出的努力。精简protobuf

1.早期的Dalvik VM内部使用short类型变量来标识方法的id,dex限制了程序的最大方法数是65535,如果超过最大限制,无法编译,把dex.force.jumbo=true添加到project.properties文件中可以通过编译,在低端手机无法安装,报错误INSTALL_FAILED_DEXOPT. 2.dex文件解决8M时,低端机安装也会出现INSTALL_FAILED_DEXOPT错误,因为dexopt用了一个固定大小的缓冲区存储所有的方法名,2.3(含)之前的版本只有5M大

Jackson工具类使用及配置指南、高性能配置(转)

Jackson使用工具类 通常,我们对JSON格式的数据,只会进行解析和封装两种,也就是JSON字符串--->Java对象以及Java对象--->JSON字符串. public class JsonUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class); private final static ObjectMappe

SpringBoot开发案例从0到1构建分布式秒杀系统

前言 最近,被推送了不少秒杀架构的文章,忙里偷闲自己也总结了一下互联网平台秒杀架构设计,当然也借鉴了不少同学的思路.俗话说,脱离案例讲架构都是耍流氓,最终使用SpringBoot模拟实现了部分秒杀场景,同时跟大家分享交流一下. 秒杀场景 秒杀场景无非就是多个用户在同时抢购一件或者多件商品,专用词汇就是所谓的高并发.现实中经常被大家喜闻乐见的场景,一群大妈抢购打折鸡蛋的画面一定不会陌生,如此场面让服务员大姐很无奈,赶上不要钱了. 业务特点 瞬间高并发.电脑旁边的小哥哥.小姐姐们如超市哄抢的大妈一般

Java记录 -79- 枚举(Enums)

枚举(Enums) JDK1.5加入了一个全新的类型的"类"--枚举类型.为此JDK1.5引入了一个新关键字enum.我们可以这样来定义一个枚举类型 Public enum Color{ Red, White, Blue } 然后可以这样来使用 Color myColor = Color.Red; 枚举类型还提供了两个很有用的静态方法 values()和valueOf().我们可以很方便的使用它们,例如: for(Color c : Color.values()) System.out

译 Programming with typesafe enums and annotations in Java 5

原文为:Programming with typesafe enums and annotations in Java 5 Annotations--Java注解 你可能会遇到这种需求:通过与元数据(描述其他数据的数据)关联来注解你Java应用程序.一直以来,Java通过transient关键字提供了一种即时注解(ad hoc annotation)机制,这允许你标识一个成员变量在序列化过程中应该被忽略.但是,直到java5才正式地引入了一种标准方式去注解程序. Java5平台提供了下面四种注解