Java's enumerated types are detailed using methods

  • 2020-04-01 04:38:19
  • OfStack

1. The background
Before enumerated types were introduced into the Java language, a common pattern for representing enumerated types was to declare a set of int constants. Previously, we usually used the public final static method to define the following code: 1 represents spring, 2 represents summer, 3 represents autumn, and 4 represents winter.


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;
}

This method is called the int enumeration pattern. But what's wrong with this model? We've all been using it for so long. Usually we write code that is safe, easy to use, and readable. First let's consider its type safety. Of course this pattern is not type safe. Let's say we design a function that passes in some value for spring, summer, autumn, and winter. But with int, we cannot guarantee that the value passed in is valid. 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(" The earth has no seasons ");
    break;
  }
  return result.toString();
 }

 public void doSomething(){
  System.out.println(this.getChineseSeason(Season.SPRING));//This is a normal scenario

  System.out.println(this.getChineseSeason(5));//This is an abnormal scenario, which leads to type insecurity
 }

The program getChineseSeason(season.spring) is how we expect to use it. GetChineseSeason (5) obviously isn't, and it compiles well, so we don't know what happens at runtime. This is clearly not consistent with the type safety of Java programs.

Let's consider the readability of this pattern. Most of The Times I use enumeration, I need to make it easy to get a string expression for an enumeration type. If we print out an 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 can cause performance problems because it relies on string comparisons, so this mode is also undesirable. The shortcomings of the int and String enumeration patterns are apparent in terms of type safety and program readability. Fortunately, since the Java1.5 release, an alternative solution has been proposed that avoids the drawbacks of the int and String enumeration patterns and provides many additional benefits. That is the enum type. The following sections describe the definitions, characteristics, application scenarios, and advantages and disadvantages of enumerated types.

Definition 2.
An enumerated type (enum type) is a type that is composed of a fixed set of constants. In Java, the keyword enum defines an enumerated type. The following is the definition of a Java enumerated type.


public enum Season {
 SPRING, SUMMER, AUTUMN, WINER;
}

Characteristics of 3.
The Java statement defining an enumerated type is simple. It has the following characteristics:

1) use the keyword enum 2) type name, such as Season 3 here) a list of allowable values, such as spring, summer, autumn, winter, seasons defined above 4) enumeration can be defined in a single file or embedded in other Java classes.
In addition to such basic requirements, users have several other options

5) enumerations can implement one or more interfaces. 6) new variables can be defined. 7) new methods can be defined
4. Apply scenarios
With the type safety example mentioned in the background, rewrite that code with an enumerated type. The code is as follows:


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 {
 
 public String getChineseSeason(Season season){
  StringBuffer result = new StringBuffer();
  switch(season){
   case SPRING :
    result.append("[ Spring, enumerate constants :" + season.name() + " And the data :" + season.getCode() + "]");
    break;
   case AUTUMN :
    result.append("[ Autumn, enumerate constants :" + season.name() + " And the data :" + season.getCode() + "]");
    break;
   case SUMMER : 
    result.append("[ Summer, enumerate constants :" + season.name() + " And the data :" + season.getCode() + "]");
    break;
   case WINTER :
    result.append("[ Winter, enumerate constants :" + season.name() + " And the data :" + season.getCode() + "]");
    break;
   default :
    result.append(" The earth has no seasons  " + 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));
  //At this point, the compilation does not pass, which guarantees type safety
 }

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

SPRING, enumeration constant :SPRING, data :1] [SUMMER, enumeration constant :SUMMER, data :2] [AUTUMN, enumeration constant :AUTUMN, data :3] [WINTER, enumeration constant :WINTER, data :4]

There is a question, why do I add fields to enumerated types? The purpose is to associate the data with its constants. For example, 1 represents spring and 2 represents summer.

5. To summarize
So when should enumerations be used? Whenever a fixed set of constants is needed, such as days of the week, seasons of the year, etc. Or a collection of all the values that we knew it contained before we compiled it. Java 1.5 enumeration can meet the requirements of the vast majority of programmers, its concise, easy-to-use characteristics are very prominent.

Use 6.
Usage 1: constant


public enum Color { 
 RED, GREEN, BLANK, YELLOW 
} 

Usage 2: switch


enum Signal { 
 GREEN, YELLOW, RED 
} 
public class TrafficLight { 
 Signal color = Signal.RED; 
 public void change() { 
  switch (color) { 
  case RED: 
   color = Signal.GREEN; 
   break; 
  case YELLOW: 
   color = Signal.RED; 
   break; 
  case GREEN: 
   color = Signal.YELLOW; 
   break; 
  } 
 } 
} 

Usage 3: add a new method to the enumeration


public enum Color { 
 RED(" red ", 1), GREEN(" green ", 2), BLANK(" white ", 3), YELLO(" yellow ", 4); 
 //Member variables
 private String name; 
 private int index; 
 //A constructor
 private Color(String name, int index) { 
  this.name = name; 
  this.index = index; 
 } 
 //Common methods
 public static String getName(int index) { 
  for (Color c : Color.values()) { 
   if (c.getIndex() == index) { 
    return c.name; 
   } 
  } 
  return null; 
 } 
 //Get set method
 public String getName() { 
  return name; 
 } 
 public void setName(String name) { 
  this.name = name; 
 } 
 public int getIndex() { 
  return index; 
 } 
 public void setIndex(int index) { 
  this.index = index; 
 } 
} 

Usage 4: override the enumeration method


public enum Color { 
 RED(" red ", 1), GREEN(" green ", 2), BLANK(" white ", 3), YELLO(" yellow ", 4); 
 //Member variables
 private String name; 
 private int index; 
 //A constructor
 private Color(String name, int index) { 
  this.name = name; 
  this.index = index; 
 } 
 //Override method
 @Override 
 public String toString() { 
  return this.index+"_"+this.name; 
 } 
} 

Usage 5: implement the interface


public interface Behaviour { 
 void print(); 
 String getInfo(); 
} 
public enum Color implements Behaviour{ 
 RED(" red ", 1), GREEN(" green ", 2), BLANK(" white ", 3), YELLO(" yellow ", 4); 
 //Member variables
 private String name; 
 private int index; 
 //A constructor
 private Color(String name, int index) { 
  this.name = name; 
  this.index = index; 
 } 
//Interface methods
 @Override 
 public String getInfo() { 
  return this.name; 
 } 
 //Interface methods
 @Override 
 public void print() { 
  System.out.println(this.index+":"+this.name); 
 } 
} 

Usage 6: use an interface to organize enumerations


public interface Food { 
 enum Coffee implements Food{ 
  BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO 
 } 
 enum Dessert implements Food{ 
  FRUIT, CAKE, GELATO 
 } 
}

The above is the entire content of this article, I hope to help you with your study.


Related articles: