preface
Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now. I know many people don’t play QQ anymore, but for a moment of nostalgia, welcome to join the six-vein Shenjian Java rookie learning group, group chat number: 549684836 encourage everyone to write blog on the road of technology
omg
Yesterday happened to encounter a small problem with enumeration, and then found that I am not so familiar with it, and then in the development, enumeration is especially used, so there is today’s article.
What is enumeration
Enumerations in Java are a type, just as their name suggests: enumerated one by one. So it generally represents a finite set type, and it’s a type, as defined in Wikipedia:
In mathematical and computer science theory, an enumeration of a set is a program that lists all the members of some finite set of sequences, or a count of objects of a particular type. The e two types often (but not always) overlap. Enumerations are a collection of named integer constants. Enumerations are common in everyday life, such as SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.
Cause of occurrence
There were no enums before Java5, so let’s take a look at how enumerations were used before Java5. Here I see a piece of design for enumerations prior to 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 the code
This method is called the Int enumeration pattern. But what’s wrong with this model? We usually write code with security, ease of use, and readability in mind. First, let’s consider its type safety. Of course, this pattern is not type-safe. Let’s say we design a function that requires passing in some value for spring, summer, fall and winter. But with an int, we cannot guarantee that the value passed in is valid. The code looks like this:
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("Seasons the Earth doesn't have.");
break;
}
return result.toString();
}
Copy the code
This does not solve the type safety problem at the source, because when we pass a value, we may pass another type, which may lead to default.
Let’s consider the readability of this pattern. Most of the time I use enumerations, I need string expressions that make it easy to get enumerations of type. If we print out the int enumeration constant, all we see is a set of numbers, which is not very useful. We might think of using String constants instead of int constants. Although it provides printable strings for these constants, it causes performance problems because it relies on string comparisons, so this pattern is also undesirable. The shortcomings of the int and String enumerated schemas are apparent from both type-safety and program readability considerations. Fortunately, since the Java1.5 release, an alternative solution has been proposed that avoids the disadvantages of the int and String enumeration pattern and provides many additional benefits. That’s an enum type.
The enumeration definition
An enum type is a legal type consisting of a fixed set of constants. In Java, the keyword enum defines an enumerated type. The following is the definition of Java enumeration types.
public enum Season {
SPRING, SUMMER, AUTUMN, WINER;
}
Copy the code
Java’s statements defining enumeration types are minimalist. It has the following characteristics:
- Keyword enum is used
- Type names, such as Season here
- A list of allowed values, such as spring, summer, fall and winter as defined above
- Enumerations can be defined individually in a file or embedded in other Java classes
- Enumerations can implement one or more interfaces.
- You can define new variables and methods
Override the enumeration method above
Here is a very formal enumerated 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() {returncode; }} public class UseSeason {/** * convert the English season to Chinese * @param season * @return
*/
public String getChineseSeason(Season season){
StringBuffer result = new StringBuffer();
switch(season){
case SPRING :
result.append("[英 文 : spring, enumeration constant :" + season.name() + ", data: + season.getCode() + "]");
break;
case AUTUMN :
result.append("[英 文 : autumn, enumeration constant :" + season.name() + ", data: + season.getCode() + "]");
break;
case SUMMER :
result.append("[英 文 : summer, enumeration constant :" + season.name() + ", data: + season.getCode() + "]");
break;
case WINTER :
result.append("[英 文 : winter, enumeration constant :" + season.name() + ", data: + season.getCode() + "]");
break;
default :
result.append("Seasons the Earth doesn't have." + season.name());
break;
}
return result.toString();
}
public void doSomething() {for(Season s : Season.values()){ System.out.println(getChineseSeason(s)); Println (getChineseSeason(5)); //System.out.println(getChineseSeason(5)); } public static void main(String[] arg){UseSeason UseSeason = new UseSeason(); useSeason.doSomething(); }}Copy the code
Enum Common methods of classes
Method names | describe |
---|---|
values() | Returns all members of an enumerated type as an array |
valueOf() | Converts a plain string to an enumeration instance |
compareTo() | Compares the order in which two enumerators are defined |
ordinal() | Gets the index location of an enumerator |
Values () method
All the members of an enumeration can be returned as an array by calling the values() method on an instance of an enumeration type, or the members of an enumeration type can be retrieved from that method.
The following example creates an enumerated type Signal with three members, and then calls the values() method to output those 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("Enumerator:"+Signal.values()[i]); }}}Copy the code
The results of
// Enumerator: GREEN // enumerator: YELLOW // enumerator: REDCopy the code
The valueOf method
Gets a single enumeration 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 the code
The results of
//GREEN
Copy the code
The ordinal () method
The index position of a member in an enumeration can be obtained by calling the ordinal() method of an enumeration type instance. The following example creates an enumerated type Signal with three members and calls the ordinal() method to output the members and their corresponding index positions.
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("Index"+Signal.values()[i].ordinal()+", value:"+Signal.values()[i]); }}}Copy the code
The results of
// index 1, value: YELLOW // index 2, value: REDCopy the code
Enumeration implements singletons
While the use of enumerations to implement singletons has not been widely adopted, enumerations of single-element types have become the best way to implement singletons.
Singleton hungry
package com.atguigu.ct.producer.controller; Public final class HungerSingleton {private static HungerSingleton instance=new HungerSingleton(); // Private constructors do not allow external new privateHungerSingleton(){} // provide a method for external calls to public static HungerSingletongetInstance() {returninstance; }}Copy the code
Lazy singleton
package com.atguigu.ct.producer.controller; Public Final Class DoubleCheckedSingleton {// Define instances but do not initialize them directly. Volatile forbids reordering. Private static DoubleCheckedSingleton instance=new DoubleCheckedSingleton(); // Private constructors do not allow external new privateDoubleCheckedSingletonPublic static DoubleCheckedSingleton (){} public static DoubleCheckedSingleton ()getInstance() {if(null==instance){
synchronized (DoubleCheckedSingleton.class){
if(null==instance) { instance = new DoubleCheckedSingleton(); }}}returninstance; }}Copy the code
A singleton of enumeration
package com.atguigu.ct.producer.controller; Public enum enumleton {// Define a singleton object INSTANCE; Public static EnumSingletongetInstance() {returnINSTANCE; }}Copy the code
In a class that needs singletons, define a static enumeration class to implement singletons of enumeration
Look at the above three ways, just look at the code to know that the singleton pattern is the simplest, because the singleton itself is privately constructed, so I recommend you to use enumeration to implement the singleton in the future
Interview questions
Does enumeration allow class inheritance?
Enumerations do not allow classes to be inherited. The Jvm already inherits Enum classes when it generates enumerations, and since the Java language is single-inheritance, there is no support for inheriting additional classes (the only inheritance quota is used by the Jvm).
Can enumerations be compared with equals?
Enumerations can be compared with equal signs. The Jvm generates a class object for each enumerated instance, which is decorated with public Static Final and initialized in the static code block as a singleton.
Can enumerations be inherited
You cannot inherit enumerations. Because when the Jvm generates an enumeration class, it declares it final.
At the end
There are only so many enumerations. Enumerations are really elegant for defining constants. Remember to use them more often in your projects
Daily for praise
Ok, everybody, that’s all for this article, you can see people here, they are real fans.
Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article
Six pulse excalibur | article “original” if there are any errors in this blog, please give criticisms, be obliged!