Learning and using java enumeration

Recently, when looking at other people’s code, I often see places where enums are used, but when I write myself, I have also thought of using enums, but there is no clear concept of when to use enums and constants. It's vague. So I specially sorted out the knowledge about enumeration for learning and use.

1. What java enumeration type

Answer by my rationale: Enumeration is a set defined by ourselves. For example, the set A={1, 2, 3} learned in mathematics. When we want to use the set A, we can only use the set The three elements 1, 2, and 3 in A cannot be used if they are not the elements in A.
Similarly, an enumeration is similar to this collection. When we define an enumeration type, we declare that there are several elements in it. When we use this enumeration, we can only use the elements it has. We cannot use the element, and the system will report an error!
Another feature of enumeration is that it can represent values. For example, the value of the first defined element is 0, and each enumeration element starts from 0 and increases one by one. At this time, this value also represents themselves, which is equivalent to two names for each element.

2. Under what circumstances to use enumerated types

2.1 When to use enumeration classes?
  Sometimes the objects of a class are limited and fixed. In this case, it is more convenient for us to use enumeration classes.
  
2.2 Why not use static constants instead of enumeration classes?

   public static final int SEASON_SPRING = 1;
  public static final int SEASON_SUMMER = 2;
  public static final int SEASON_FALL = 3;
  public static final int SEASON_WINTER = 4;

 Enumeration classes are more intuitive and type safe. The use of constants has the following disadvantages:
  1. Unsafe types. If a method requires the season parameter to be passed in, if a constant is used, the formal parameter is of type int. Developers can pass in any type of int type value, but if it is an enumeration type, it can only be passed to the enumeration class Included objects.
  2. There is no namespace. Developers should start with SEASON_ when naming them, so that when another developer looks at this code, they will know that these four constants represent the seasons.

2.3 Commonly used places:
We need to get a value from another function, but this value can only be in a range, at this time we can use enumeration to define this range. Limit the value that another function can pass in, only the elements in the enumeration type

3. Simple use and attention points of enumeration class

package enumcase;
  public enum SeasonEnum {
  SPRING,SUMMER,FALL,WINTER;
  }

Then you can use it like this: SeasonEnum currentSeason = SeasonEnum .SUMMER

Note:
(1)
Enum has the same status as class and interface (2) The enumeration class defined by enum inherits java.lang.Enum by default, instead of inheriting the Object class. Enumeration classes can implement one or more interfaces.
(3) All instances of the enumeration class must be displayed on the first line, without using the new keyword, and without explicitly calling the constructor. Automatically add public static final decoration.
(4) Non-abstract enumeration classes that use enum definitions are finalized by default and cannot be inherited.
(5) The constructor of the enumeration class can only be private.

3.1 Properties and methods can also be defined in the enumeration class, but they are static and non-static.

package enumcase;
  public enum SeasonEnum {
      SPRING("春天"),
      SUMMER("夏天"),
      FALL("秋天"),
      WINTER("冬天");
  
  private final String name;
  
  private SeasonEnum(String name)
  {
     this.name = name;
  }
  public String getName() {
    return name;
  }
 }

In fact, when the enumeration class instance is written in the first line, the constructor is called by default, so parameters need to be passed in here, because there is no explicit declaration of the parameterless constructor, only the constructor with parameters can be called.
  The constructor needs to be defined as private so that such objects cannot be declared elsewhere. Enumeration classes should usually be designed as immutable classes, and its Field should not be changed, which will be safer and the code more concise. So we modify the Field with private final.

3.2 enumeration class traversing
enumerated type provides two useful static method values () and valueOf () we can easily use them
for example:

 for(SeasonEnum s : SeasonEnum .values())
     System.out.println(s);

3.3 The expression in the switch statement can be an enumeration value

package enumcase;
public class SeasonTest {
    
    
 public void judge(SeasonEnum s){
  switch(s){
      case SPRING:
        System.out.println("春天适合踏青。");
      break;
      case SUMMER:
        System.out.println("夏天要去游泳啦。");
      break;
      case FALL:
        System.out.println("秋天一定要去旅游哦。");
      break;
      case WINTER:
        System.out.println("冬天要是下雪就好啦。");
      break;
  }
 }
 
public static void main(String[] args) {
  SeasonEnum s = SeasonEnum.SPRING;
  SeasonTest test = new SeasonTest();
  test.judge(s);
  }
}

3.4 The definition of an enumeration type is essentially to define a category, but many details are completed by the compiler for us, so to some extent, the function of the enum keyword is like class or interface

3.5 The enumeration class defined by enum inherits java.lang.Enum by default instead of inheriting the Object class

When we use "enum" to define an enumeration type, in fact the type we defined inherits from the java.lang.Enum type, and the members of the enumeration are actually an instance (Instance) of the enumeration type we defined. They are preset as final, so we cannot change them. They are also static members, so we can use them directly through the type name. Of course, the most important thing is that they are all public. That is, each enumeration type we define inherits from the java.lang.Enum class, and each member in the enumeration is public static final by default.
The members of each enumeration are actually an instance of the enumeration type we defined. In other words, when an enumeration type is defined, it can be determined at compile time how many instances of the enumeration type are and what they are. During runtime, we can no longer use the enumeration to create new instances, these instances have been completely determined during compilation. So in: SeasonEnum currentSeason = SeasonEnum .SUMMER, there is no new SeasonEnum (). Direct assignment

3.6 Check permissions

For example, a manager, employee, or customer's permission to use a tool is generally handled by enumeration because it can be used to control the parameters passed in for judgment can only be the number of the enumeration type, thereby limiting the passed parameters.

package Enum;

public class AccessControl {
    
    
    public static boolean checkRight(AccessRight access){
        if(access == AccessRight.MANAGER){
            return true;
        }
        else if(access == AccessRight.DEPARMENT){
           return false;
        }else {
          return false;
        }

    public static void main(String[] args) {
        System.out.println(checkRight(AccessRight.DEPARMENT));
    }
}

enum AccessRight{
MANAGER,DEPARMENT,EMPLOYEE;

In this way, only AccessRight type parameters can be passed, and other parameters are illegal.

3.7 Convert String type to enumeration type

static <T extends Enum<T>> T 
valueOf(Class<T> enumType, String name) 

Returns the enum constant of the specified enum type with the specified name.

You can use AccessRight access = AccessRight.valueOf("MANAGER");//As long as there is an element of MANAGER in AccessRight, you can return this element, that is, convert the String type to the AccessRight type

4. Reference website

So far, I have learned a lot from the enumeration, and I have sorted out some things on the Internet a little bit. Below I am some websites that I learn from

https://www.douban.com/note/512891241/
http://blog.sina.com.cn/s/blog_4adc4b090101dtxp.html
http://blog.sina.com.cn/s/blog_697b968901013ih1.html

Guess you like

Origin blog.csdn.net/android_freshman/article/details/52223542