# Java enumeration based on Java

Posted by ben2k8 on Mon, 07 Mar 2022 23:22:58 +0100

## Ramble

Yesterday, I happened to encounter a small problem with enumeration, and then found that I am not so familiar with it. Then in development, enumeration is used very much, so I have today's article.

## What is enumeration

Enumeration in Java is a type, just as the name suggests: it is enumerated one by one. Therefore, it generally represents a limited set type. It is a type. The definition given in Wikipedia is:

In mathematical and computer science theory, the enumeration of a set is a program that lists all members of some finite sequence set, or a count of a specific type of object. The two types often (but not always) overlap. Enumeration is a collection of named integer constants. Enumeration is very common in daily life. For example, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY are enumerations.

If you want to learn Java, I'll share some java learning materials for you. You don't have to waste time searching everywhere. I've sorted out the materials from Java introduction to proficiency. These materials are the latest java learning route, java written test questions, Java interview questions, Java zero foundation to proficiency video courses, java development tools and Java hands-on projects I've sorted out in recent years, Java e-books, java learning notes, PDF document tutorials, java programmer's experience, Java resume template, etc. these materials will be very helpful for you to learn java next. Every JAVA beginner is necessary. Please enter my website Java technology qq communication group Download by yourself. All materials are in the group file. You should communicate and learn more with you.

## Causes of occurrence

Before Java 5, there was no enum, so let's take a look at the use scenario of enumeration before Java 5. How to solve it? Here I see a design scheme of enumeration before Java 1.4:

```public class Season {
public static final int SPRING = 1;
public static final int SUMMER = 2;
public static final int AUTUMN = 3;
public static final int WINTER = 4;
}
Copy code```

This method is called int enumeration mode. But what's wrong with this model? Usually the code we write will consider its security, ease of use and readability. First, let's consider its type security. Of course, this pattern is not type safe. For example, we design a function that requires a value of spring, summer, autumn and winter to be passed in. However, with int type, we cannot guarantee that the value passed in is legal. The code is as follows:

```private String getChineseSeason(int season){
StringBuffer result = new StringBuffer();
switch(season){
case Season.SPRING :
result.append("spring");
break;
case Season.SUMMER :
result.append("summer");
break;
case Season.AUTUMN :
result.append("autumn");
break;
case Season.WINTER :
result.append("winter");
break;
default :
result.append("There are no seasons on earth");
break;
}
return result.toString();
}
Copy code```

When we pass values, we may pass other types, which may lead to default. Therefore, this does not solve the problem of type safety at the source.

Next, let's consider the readability of this pattern. In most cases of using enumeration, I need to easily get the String expression of enumeration type. If the int enumeration constant is printed out, what we see is a set of numbers, which is of little use. We might think of using String constants instead of int constants. Although it provides printable strings for these constants, it can cause performance problems because it depends on String comparison operation, so this mode is also undesirable. Considering both type safety and program readability, the disadvantages of int and String enumeration modes are exposed. Fortunately, from Java 1 Since the release of 5, an alternative solution has been proposed, which can avoid the disadvantages of int and String enumeration mode and provide many additional benefits. That is enum type.

## Enumeration Definition

enum type refers to a legal type composed of a fixed set of constants. In Java, an enumeration type is defined by the keyword enum. The following is the definition of Java enumeration type.

```public enum Season {
SPRING, SUMMER, AUTUMN, WINER;
}
Copy code```

The Java statement defining enumeration types is very simple. It has the following characteristics:

• Use keyword enum
• Type name, such as Season here
• A string of allowable values, such as the four seasons of spring, summer, autumn and winter defined above
• Enumerations can be defined in a single file or embedded in other Java classes
• Enumeration can implement one or more interfaces
• You can define new variables and methods

## Override the enumeration method above

The following is a very standard enumeration type

```public enum Season {
SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4);

private int code;
private Season(int code){
this.code = code;
}

public int getCode(){
return code;
}
}
public class UseSeason {
/**
* Convert English seasons into Chinese seasons
* @param season
* @return
*/
public String getChineseSeason(Season season){
StringBuffer result = new StringBuffer();
switch(season){
case SPRING :
result.append("[English: spring, enumeration constant:" + season.name() + "，data:" + season.getCode() + "]");
break;
case AUTUMN :
result.append("[English: autumn, enumeration constant:" + season.name() + "，data:" + season.getCode() + "]");
break;
case SUMMER :
result.append("[English: summer, enumeration constant:" + season.name() + "，data:" + season.getCode() + "]");
break;
case WINTER :
result.append("[English: winter, enumeration constant:" + season.name() + "，data:" + season.getCode() + "]");
break;
default :
result.append("There are no seasons on earth " + season.name());
break;
}
return result.toString();
}

public void doSomething(){
for(Season s : Season.values()){
System.out.println(getChineseSeason(s));//This is a normal scenario
}
//System.out.println(getChineseSeason(5));
//The compilation fails here, which ensures type safety
}

public static void main(String[] arg){
UseSeason useSeason = new UseSeason();
useSeason.doSomething();
}
}
Copy code```

## Common methods of Enum class

Method namedescribe
values()Returns all members of an enumerated type as an array
valueOf()Converts a normal string to an enumerated instance
compareTo()Compare the order of two enumeration members when they are defined
ordinal()Gets the index location of the enumeration member

### values() method

By calling the values() method of the enumeration type instance, you can return all the members of the enumeration in the form of an array, or you can obtain the members of the enumeration type through this method.

The following example creates an enumeration type Signal containing 3 members, and then calls the values() method to export these members.

```public enum Signal {

//Define an enumeration type
GREEN,YELLOW,RED;

public static void main(String[] args)
{
for(int i=0;i<Signal.values().length;i++)
{
System.out.println("Enumeration members:"+Signal.values()[i]);
}
}

}

Copy code```

result

```//Enumeration member: GREEN
//Enumeration member: YELLOW
//Enum members: RED
Copy code```

### valueOf method

Get a single enumerated object from a string

```public enum Signal {

//Define an enumeration type
GREEN,YELLOW,RED;

public static void main(String[] args)
{
Signal green = Signal.valueOf("GREEN");
System.out.println(green);
}

}
Copy code```

result

```//GREEN

Copy code```

### ordinal() method

The index position of a member in the enumeration can be obtained by calling the ordinal() method of the enumeration type instance. The following example creates an enumeration type Signal containing 3 members, and then calls the ordinal() method to export the members and corresponding index locations.

```public class TestEnum1
{
enum Signal
{
//Define an enumeration type
GREEN,YELLOW,RED;
}
public static void main(String[] args)
{
for(int i=0;i<Signal.values().length;i++)
{
System.out.println("Indexes"+Signal.values()[i].ordinal()+"，Value:"+Signal.values()[i]);
}
}
}
Copy code```

result

```//Index 0, value: GREEN
//Index 1, value: YELLOW
//Index 2, value: RED
Copy code```

## Enumeration implementation singleton

Although the method of using enumeration to realize Singleton has not been widely used, the enumeration type of single element has become the best method to realize Singleton.

### Single case hungry Chinese style

```package com.atguigu.ct.producer.controller;
//final is not allowed to be inherited
public final class HungerSingleton {

private static HungerSingleton instance=new HungerSingleton();
//External new is not allowed for private constructors
private HungerSingleton(){
}
//Provide a method for external calls
public static HungerSingleton getInstance(){
return instance;
}

}
Copy code```

### Lazy single example

```package com.atguigu.ct.producer.controller;
//final cannot be inherited
public final class DoubleCheckedSingleton {
//The instance is defined but not initialized directly. volatile prohibits reordering operations to avoid null pointer exceptions
private static DoubleCheckedSingleton instance=new DoubleCheckedSingleton();

//External new is not allowed for private constructors
private DoubleCheckedSingleton(){
}

//Externally provided methods are used to obtain singleton objects
public static DoubleCheckedSingleton getInstance(){
if(null==instance){
synchronized (DoubleCheckedSingleton.class){
if (null==instance) {
instance = new DoubleCheckedSingleton();
}
}
}
return instance;
}

}

Copy code```

### Singleton of enumeration

```package com.atguigu.ct.producer.controller;

public enum EnumSingleton {
//Define a singleton object
INSTANCE;
//Method of obtaining singleton object
public  static EnumSingleton getInstance(){
return INSTANCE;
}

}
Copy code```

In another class that needs singleton, define a static enumeration class to implement singleton enumeration

Looking at the above three methods, just look at the code to know that the singleton mode is the simplest. Because the singleton itself is privately constructed, it is recommended that you use enumeration to implement the singleton in the future

## Interview questions

### Are enumerations allowed to inherit classes?

Enumeration does not allow inherited classes. The Jvm has inherited Enum class when generating enumeration. Because the Java language is single inheritance, it does not support inheriting additional classes (the only inheritance quota is used by the Jvm).

### Can enumerations be compared with equal signs?

Enumerations can be compared with equal signs. The Jvm will generate a class object for each enumerated instance. This class object is decorated with public static final and initialized in the static code block. It is a singleton.

### Can enumeration be inherited by others

Enumeration cannot be inherited. Because when the Jvm generates the enumeration class, it declares it as final.

## ending

In fact, there are so many enumerations. When defining constants, enumerations are really elegant. Remember to use them more in the project

# last

If you want to learn Java, I'll share some java learning materials for you. You don't have to waste time searching everywhere. I've sorted out the materials from Java introduction to proficiency. These materials are the latest java learning route, java written test questions, Java interview questions, Java zero foundation to proficiency video courses, java development tools and Java hands-on projects I've sorted out in recent years, Java e-books, java learning notes, PDF document tutorials, java programmer's experience, Java resume template, etc. these materials will be very helpful for you to learn java next. Every JAVA beginner is necessary. Please enter my website Java technology qq communication group Download by yourself. All materials are in the group file. You should communicate and learn more with you.