知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

      • Theory:Functional decomposition
      • Theory:Paradigms
      • Theory:Overloading
      • Theory:Write, compile, and run
      • Theory:Annotations basics
      • Theory:JVM, JRE, and JDK
      • Theory:Jave Archive
      • Theory:Running programs on your computer
      • Theory:Enums in Java
        • Defining an enum
        • Methods for processing enums
        • Enumerations in the switch statement
        • Iterating over an enum
        • Conclusion
      • Theory:Fields and methods in enum
      • Theory:StringBuilder
      • Theory:Immutability
      • Theory:Boxing and unboxing
      • Theory:Introduction to generic programming
      • Theory:Generics and Object
      • Theory:What are collections
      • Theory:The collections Framework overview
      • Theory:ArrayList
      • Theory:The List interface
      • Theory:Comparable
      • Theory:Processing strings
      • Theory:Initialization blocks
      • Theory:Introduction to API
      • Theory:Generic methods
    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 应知
Jim
2022-09-03
目录

Theory:Enums in Java

When a variable can only take one out of a small set of possible values, it's a good idea to use enums in a program. Enum is a special keyword short for enumeration that allows us to create a list of constants grouped by their content: seasons, colors, states, etc. When we store a bunch of constants in one place and handle them together**,** it helps us to avoid errors, and it makes the code look more readable and clear.

Now, let's look closer at how enums work.

# Defining an enum

We can create our own enumeration in a way that is similar to declaring classes. According to the Java Code Convention, constants in an enum are written in uppercase letters. All constants should be separated with commas. Take a look at the example enum Season:

public enum Season {
    SPRING, SUMMER, AUTUMN, WINTER // four instances
}
1
2
3

提示

It is possible to declare an enum inside the class. In this case, we don't need to use public modifier in the enum declaration.

In general, an enum can be considered as a class with predefined instances. Here, we have four instances of seasons SPRING, SUMMER, AUTUMN and WINTER inside the storage Season. If we want to extend the list of constants, we can simply add another instance in our enum: mid-winter, Australian winter, etc. Don't forget that in real life they have to make sense.

Now that we've got an idea of how to define basic enums, let's learn how to use them in a program.

# Methods for processing enums

Suppose that we have to write a program with an enum that displays three possible user statuses. Let's create an enum UserStatus with these statuses:

public enum UserStatus {
    PENDING, ACTIVE, BLOCKED
}
1
2
3

And now we initialize a variable of the type UserStatus from the previous example:

UserStatus active = UserStatus.ACTIVE;
1

Each enum value has a name that can be accessed by using the method name():

System.out.println(active.name()); // ACTIVE
1

Sometimes, we may need to access an enumeration instance by its name. This can be done with the valueOf() method which provides us with another way to initialize a variable:

UserStatus blocked = UserStatus.valueOf("BLOCKED"); // BLOCKED
1

An important thing to remember about this method is that it is case-sensitive**.** That means that if the given string doesn't exactly match any constant, we will get an IllegalArgumentException.

UserStatus blocked = UserStatus.valueOf("blocked"); // IllegalArgumentException, valueOf is case-sensitive
1

If we want to look at all constants of an enumeration, we can get them in an array by using the values() method:

UserStatus[] statuses = UserStatus.values(); // [PENDING, ACTIVE, BLOCKED]
1

Another method called ordinal() returns the ordinal position of an instance of an enum:

System.out.println(active.ordinal()); // 1 (starting with 0)
System.out.println(UserStatus.BLOCKED.ordinal()); // 2
1
2

Although an enum is a reference type, two variables can be correctly compared by using both the equals method and the operator ==.

System.out.println(active.equals(UserStatus.ACTIVE)); // true
System.out.println(active == UserStatus.ACTIVE); // true
1
2

# Enumerations in the switch statement

An enum can be successfully used in the switch statement. Depending on the status, our program can perform different actions indicated by the switch statement. In this case, it prints out different responses:

UserStatus status = ... // some status
 
switch (status) {
    case PENDING:
        System.out.println("You need to wait a little.");
        break;
    case ACTIVE:
        System.out.println("No problems, you may pass here.");
        break;
    case BLOCKED:
        System.out.println("Stop! You can't pass here.");
        break;
    default:
        System.out.println("Unsupported enum constant.");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

The message that our program outputs depends on the value of the variable status.

# Iterating over an enum

One of the best ways to iterate over an enum is to use a for or a for-each loop. Let's apply it to our sample enum:

    for (UserStatus status : UserStatus.values()) {
        System.out.println(status);
    }
/* the output is
PENDING 
ACTIVE
BLOCKED
*/
        
1
2
3
4
5
6
7
8
9

Here, we used the values() method to return an array of enum values. This loop comes in handy when iterating over enums with a large number of constants.

# Conclusion

An enum is a special keyword that helps us to define named constants grouped together according to their content. By defining enums you can make code more readable and avoid invalid values being passed in. The number of constants in an enum may be extended whenever we want. Also, you can use the name(), valueOf(), ordinal() and equals() methods to process the enum. switch statements and for-each loops are widely used while working with enums in simple programs.

Now you know how to use it, so get ready for some practice!

编辑 (opens new window)
#Java#Enum
上次更新: 2022/09/26, 16:55:15
Theory:Running programs on your computer
Theory:Fields and methods in enum

← Theory:Running programs on your computer Theory:Fields and methods in enum→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式