This is the 27th day of my participation in the August Genwen Challenge.More challenges in August

preface

  • 8.27
  • Don’t stop my music and study
  • The goal is to become a comprehensive talent in operation and development

The target

  1. What is an enumerated class
  2. Why do you need enumerated classes
  3. How do I customize enumerated classes and how do I use them
  4. Enum Common methods of classes

1. What are enumerated classes

In mathematics and computer science, an enumeration of a set is a program that lists all the members of some finite set of sequences, or a technique for objects of a particular type.

An enumeration is a named collection of integer constants. Enumerations are very common in life. Enumerations are as follows:

  • The day of the week:SUNDAY,MONDAY,TUESTDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAYIt’s an enumeration;
  • Gender:MALE(male),female(female) is also an enumeration;
  • Order status:PAIDED(paid),UNPAIDED(unpaid),FINISHED(Completed),CANCELED(Cancelled).

Simply put, an enumeration class is a class that can represent enumerations. When a class has a finite number of objects, we can define an enumeration class to hold those objects.

2. Why are enumerated classes needed

If we want to define Monday through Sunday in a class instead of using enumerated classes, we might need to use constants in the class to indicate it, as shown in the following example:

public class Weekday {
    public static final int MONDAY = 1;
    public static final int TUESDAY = 2;
    public static final int WEDNESDAY = 3;
    public static final int THURSDAY = 4;
    public static final int FRIDAY = 5;
    public static final int SATURDAY = 6;
    public static final int SUNDAY = 7;
}
Copy the code

The problem with using a set of constants to represent a collection of enumerations is that the compiler cannot detect whether the range of each value is valid, for example:

int day = 0; // Assume the value of day is 0
if (day == Weekday.MON) {
    System.out.println("It's Monday");
}
Copy the code

Obviously, 0 is not in the range (1 to 7) represented by these constant values, but the compiler does not give a hint, and such encodings are highly discouraged.

When we need to define a set of constants in development, we recommend using enumerated classes. Let’s look at how to define an enumerated class.

3. How do I customize enumerated classes

After Java 5.0, you can define an enumerated class using the EUNM keyword

The following steps are usually required:

  1. useenumThe keyword defines an enumerated class that implicitly inherits fromjava.lang.EnumClass;
  2. Inside the enumeration class, multiple objects of the current enumeration class are provided, separated by commas, and the last object ends with a semicolon;
  3. Declare properties and constructors of enumerated classes, assigning values to properties in constructors;
  4. providegetterMethod, due toEnumClass overrides thetoString()Method, so we generally don’t need to rewrite it ourselves.
  5. The toString () method returns the value of the Number object as a string.

Specific examples are as follows:

package com.caq.exception;

import java.awt.*;

public class Test2 {
    public static void main(String[] args) {
        Test test1 = Test.man;
        System.out.println(test1);
        System.out.println(test1.getSexName());
        System.out.println(Test.woman.getSexName());
        System.out.println(Test.unknow.getSexName());
    }

    enum Test{
        // Generate enumeration classes using the enum keyword
        //1. Enumeration classes provide multiple objects inside, separated by commas
        //2. Declare the genus of the enumerated class
        //3. Write a constructor to assign a value to the genus type
        //3. Provide Getter methods to get genus types (encapsulated knowledge)

        / / 1.
        man("Male"),
        woman("Female"),
        unknow("Unknown");

        / / 2.
        private final String sexName;

        / / 3.
        Test(String sexName){
            this.sexName=sexName;
        }

        public String getSexName(a) {
            returnsexName; }}}Copy the code

Running results:

Man Male female unknownCopy the code

4. An Enum

Enum class is a common base class for Java language enumeration types.Enum classes are implicitly inherited from Enum classes using the Enum keyword.

  • values(): returns an array of objects of enumerated type. This method can easily traverse all enumeration values;
  • valueOf(): Converts a string to the corresponding enumerated class object. Requires that the string must be the “name” of an enumeration class object, or thrown if it is notIllegalArguementException;
  • toString(): Returns the name of the current enumeration class object constant.

These three methods are relatively simple to use, so we write them in an example with the following code:

package com.caq.exception;

public class Test2 {
    public static void main(String[] args) {
        Test test1 = Test.man;
        System.out.println("Call toString method");
        System.out.println(test1.toString());
        
        System.out.println("Call values method");
        Test[] values = Test.values();
        for (Test value : values){
            System.out.println(value);
        }
        
        System.out.println("Call values method");
        Test test2 = Test.valueOf("man");
        System.out.println(test2);
    }

    enum Test{
        // Generate enumeration classes using the enum keyword
        //1. Enumeration classes provide multiple objects inside, separated by commas
        //2. Declare the genus of the enumerated class
        //3. Write a constructor to assign a value to the genus type
        //3. Provide Getter methods to get genus types (encapsulated knowledge)

        / / 1.
        man("Male"),
        woman("Female"),
        unknow("Unknown");

        / / 2.
        private final String sexName;

        / / 3.
        Test(String sexName){
            this.sexName=sexName;
        }

        public String getSexName(a) {
            returnsexName; }}}Copy the code

Running results:

Call toString man call values man woman unknow Call values manCopy the code

Note that when the valuOf() method is called, the “name” of the object we pass, which does not exist in the enumeration class, will throw a runtime exception: IllegalArgumentException

package com.caq.exception;

public class Test2 {
    public static void main(String[] args) {
        Test test1 = Test.man;

        System.out.println("Call values method");
        Test test2 = Test.valueOf("man1");
        System.out.println(test2);
    }

    enum Test{
        // Generate enumeration classes using the enum keyword
        //1. Enumeration classes provide multiple objects inside, separated by commas
        //2. Declare the genus of the enumerated class
        //3. Write a constructor to assign a value to the genus type
        //3. Provide Getter methods to get genus types (encapsulated knowledge)

        / / 1.
        man("Male"),
        woman("Female"),
        unknow("Unknown");

        / / 2.
        private final String sexName;

        / / 3.
        Test(String sexName){
            this.sexName=sexName;
        }

        public String getSexName(a) {
            returnsexName; }}}Copy the code

Running results:

Call the values method Exceptionin thread "main" java.lang.IllegalArgumentException: No enum constant com.caq.exception.Test2.Test.man1
	at java.lang.Enum.valueOf(Enum.java:238)
	at com.caq.exception.Test2$Test.valueOf(Test2.java:12)
	at com.caq.exception.Test2.main(Test2.java:8)
Copy the code

5. Summary

An enumeration class is a class that can represent enumerations

When a class has a finite number of objects, we can define an enumerated class to hold those objects.

Using enumerated classes circumvents the problem that the compiler cannot detect whether the range of each value is valid.

Use the enum keyword to define enumerated classes.

All enumerated classes defined by the enum keyword inherit from the java.lang. enum class, and understand the use of common methods for this class.