Java Enums
2015-06-16 01:57
447 查看
Table of Contents
Enum ExampleEnums in if Statements
Enums in switch Statements
Enum Iteration
Enum Fields
Enum Methods
Enum Miscellaneous Details
A 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
enumkeyword which is used in place of
classor
interface. The Java
enumkeyword 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
levelvariable is of the type
Levelwhich is the Java enum type defined in the example above. The
levelvariable can take one of the
Levelenum constants as value (
HIGH,
MEDIUMor
LOW). In this case
levelis 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 anif-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
levelvariable against each of the possible enum constants in the
Levelenum.
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 Javaswitchstatement 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
levelvariable 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 staticvalues()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 finalconstants.
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
intfield. When the constant enum values are defined, an
intvalue 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
3which is the value of the
levelCodefield 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
finalyou 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 thejava.lang.Enumclass 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;
相关文章推荐
- java中读取配置文件
- Java concurrency (multi-threading) - Tutorial
- 我的Java开发学习之旅------>解惑Java进行三目运算时的自动类型转换
- Split / Partition a collection into smaller collections - Java - Tutorial
- How to implement an ArrayList structure in Java - Tutorial
- How to implement common datastructures (List, Stack, Map) in plain Java - Tutorial
- java中hashcode()和equals()的详解
- Java Logging: LogManager
- Java Logging: Configuration
- Java Logging: LogRecord
- Java中Comparable和Comparator实现对象比较
- Java Logging API - Tutorial
- Spring如何解决循环依赖
- Java Logging: Handlers
- Java事件监听机制
- Java Logging: Filters
- Java Logging: Formatters
- Java Logging: Log Levels
- Java Logging: Logger Hierarchy
- Java Logging: Logger