All knowledge system articles,GitHubWelcome Star! Thank you again and wish you a speedy entry into Dachang!

GitHub address: github.com/Ziphtracks/…

Understand Java enumerations in depth


What is enumeration

1.1 What is enumeration?

As for enumerations, let’s start with enumerations in real life and then move on to Enumerations in Java, which have similar meanings.

When it comes to the enumeration of life, if we play dice in the game, in our hands, there are two dice, requires two dice throw points and must be greater than the probability of 6, so in this instance, we will need to use the enumeration method to enumerate the dice points to all of the possible, and then according to the list of possible, calculate the probability.

Some of you might realize, well, this is math, right? This is probability and statistics in mathematics. Yes, our enumeration method is commonly used in probability statistics.

1.2 Enumeration classes in Java

Java 5.0 introduced enumerations, which restrict variables to predefined values. Using enumerations can reduce bugs in your code and facilitate many scenarios.

Java enumeration syntax

A declaration in an enumeration class

Access figureenumEnumerator {enumerator, enumerator,... };Copy the code

The declaration of an enumeration in a class

Access modifierclassThe name of the class{
    enumEnumerator {enumerator, enumerator,... }}Copy the code

Java enumeration class usage rules and application scenarios

3.1 Rules for using Java enumeration classes

As for enumerations, you already know that enumerations are the same in Java. There are also specific rules and scenarios for the use of enumerated classes in Java. If you don’t understand the following rules, don’t worry, continue to learn you will understand, because I will explain these rules in the following. Here are a few rules:

  • Class is a finite number of objects.
  • Enumerations are recommended when you need to define a set of constants.
  • If there is only one object in the enumerated class, it can be used as an implementation of the singleton pattern.
  • Enumerated classes cannot be inherited
  • Enumeration classes cannot be created by new alone
  • An enumeration member in an enumeration class is used.Separated, used between enumerators_separated
  • If there is only one or more enumerators in an enumeration class and nothing else, what are we using.At the same time. Finally, you can omit;Terminator.

Note: If you don’t know much about enumerating singleton design patterns, you will definitely learn something unexpected. Trust me!

3.2 Application Scenarios of Java Enumeration Classes

Based on the rules for using enumerations in Java, there are several scenarios for using enumerations, as follows:

  • Week: Monday, Tuesday, Wednesday, Thursday, Firday, Saturday, Sunday
  • Gender: Man, Woman
  • Season: Spring, Summer, Autumn, Winter
  • Payment methods: Cash, WeChatPay, Alipay, BankCard, CreditCard
  • The order status: Nonpayment, Paid, Fulfilled, Delivered, Return and Checked
  • Thread states: do Establish, Ready, Run, Obstruct, Die
  • And so on…

Enumeration class basic usage step analysis

Let’s explain the following two rules. We’ve already seen enumerations in action. Java enumeration is no exception, is also listed one by one to facilitate our use of one or more. This is a bit like our multi-check box. We put all the options we need to use behind each multi-check box. When we use it, we just need to check the check box we need, which represents the content behind the multi-check box we need to be selected.

So how are enumerated classes used in Java?

Here we simply simulate a scene, assuming that your girlfriend likes to drink some cold drinks or hot milk tea and other drinks, there are also many drinks shops like Michelle Ice City in life. When you buy your girlfriend her favorite bubble tea, the waiter will ask you if you want a large, medium or small cup. Of course, to satisfy your girlfriend, you usually go for the grande. This means customers are not allowed to order drinks outside the rules.

Note: If you are a beginner or don’t know how to use enumerations, please read on.

So, I’m going to use Java code to implement this scenario.

First, create the enumeration class. Add large, medium and small cups for pearl milk tea respectively.

package com.mylifes1110.java;

/ * * *@ClassName PearlMilkTea
 * @DescriptionAdd three cup shapes for pearl milk tea: large, medium and small@Author Ziph
 * @Date 2020/6/8
 * @Since1.8 * /
public enum PearlMilkTea {
    // Note: there are only enumerators in the enumeration class, which I omit here; terminator
    SMALL, MEDIUM, LARGE
}
Copy the code

Secondly, the pearl milk tea object is created, and there is a method to judge the large, medium and small cups in the enumeration class. Finally print girlfriend drink which cup of pearl milk tea!

package com.mylifes1110.test;

import com.mylifes1110.java.PearlMilkTea;

/ * * *@ClassName PearlMilkTeaTest
 * @DescriptionWhich cup size of bubble tea to buy for your girlfriend (large by default) *@Author Ziph
 * @Date 2020/6/8
 * @Since1.8 * /
public class PearlMilkTeaTest {
    public static void main(String[] args) {
        // Create a large bubble tea object
        PearlMilkTea pearlMilkTea = PearlMilkTea.LARGE;
        PearlMilkTeaTest.drinkSize(pearlMilkTea);
    }

    // Decide which cup of bubble tea to buy for your girlfriend
    public static void drinkSize(PearlMilkTea pearlMilkTea) {
        if (pearlMilkTea == PearlMilkTea.LARGE) {
            System.out.println("I bought a large bubble tea for my girlfriend!");
        } else if (pearlMilkTea == PearlMilkTea.MEDIUM) {
            System.out.println("I bought a medium bubble tea for my girlfriend!");
        } else {
            System.out.println("I bought a small cup of bubble tea for my girlfriend!"); }}}Copy the code

Although we have looked at the basic use of enumerations in classes, we have also introduced an enumeration defined in a class in the syntax. It’s good to do it here. As follows:

public class PearlMilkTea {
    enum DrinkSize {
        SMALL,
        MEDIUM, 
        LARGE
    }
}
Copy the code

Create enum enum classes in class. Consider that the code in the previous example doesn’t make sense. Why? Because we write code that follows the single responsibility principle and a naming convention that tells you what to do. So, I wrote the code to list the large, medium, and small cup enumerators in the bubble tea enumerator class. Therefore, according to the specification, we cannot have enumeration related to cup type in pearl milk tea. After all, all kinds of drinks we drink in this kind of drink shop in life have these three cup types, so we need to write an enumeration class in all kinds of drinks, which is obviously very unreasonable.

To make it more reasonable, we can create a drink enumeration class and a cup type enumeration class by subdividing the drinks and applying them in pairs. Maybe some friends will ask me why I say these reasonable is not reasonable? Because this is the feeling of self enumeration class application of the thought of bedding, so you taste, you fine taste!

5. Custom enumerated classes

5.1 Steps for customizing enumeration classes

As for the basic use of enumeration classes in Chapter 4, you may be unfamiliar with enumeration and do not know why to create enumeration objects in this way. Next, I’ll show you how to customize enumerated classes using constants to see if that works.

Since I covered so many scenarios for using enumerators in Chapter 3 above, let’s pick a classic spring, summer, fall and winter to implement custom enumerators.

First, we create a season class that provides properties, private constructors, spring/summer/fall/winter constants, Getter methods, and toString methods as follows:

package com.mylifes1110.java;

/** * Custom season enumeration class */
public class Season {
    // Declare the Season object as a private final modifier
    private final String seasonName;

    // Privatize the constructor and assign a value to the object
    private Season(String seasonName) {
        this.seasonName = seasonName;
    }

    // Provides multiple objects for the current enumeration, which is a public static final modifier
    public static final Season SPRING = new Season("Spring");
    public static final Season SUMMER = new Season("Summer");
    public static final Season AUTUMN = new Season("Autumn");
    public static final Season WINTER = new Season("Winter");

    // Provides the outside world to get the properties of the enumerated object through getter methods
    public String getSeasonName(a) {
        return seasonName;
    }

    // Override the toString method to print out the enumeration results
    @Override
    public String toString(a) {
        return "Season{" +
                "seasonName='" + seasonName + '\' ' +
                '} '; }}Copy the code

Next, we create a test class to use the custom enumerated class to create objects. From this point of view, we can call constant objects according to the class name!

package com.mylifes1110.test;

import com.mylifes1110.java.Season;

/** * Test class */
public class SeasonTest {
    public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); }}Copy the code

The final printable result is the spring object, since we overwrite the toString method, the contents of the visible object.

5.2 Using classes with enumerated parameters

If you didn’t understand the basics of using Java enumerators in Chapter 3, you’ll probably understand custom enumerators as well. But did you notice that our custom enumerated classes use objects with parameters? So how do we use real enumerated classes to implement enumerated classes with parameters? Keep watching!

Here I modify the custom enumeration class to use parameter objects for the enum enum class implementation. As follows:

package com.mylifes1110.java;

public enum Season {
    SPRING("Spring"),
    SUMMER("Summer"),
    AUTUMN("Autumn"),
    WINTER("Winter");

    private final String seasonName;

    Season1(String seasonName) {
        this.seasonName = seasonName;
    }

    public String getSeasonName(a) {
        returnseasonName; }}Copy the code

I don’t know if you noticed anything missing, but the missing part is actually the part where we create the constant object, and I didn’t override the toString method in this enumerated class, and I’ll tell you why.

Note: Enumeration objects are separated by a comma!

Second, to create the test class that created the enumerated class, we test the following and see the result printed without overriding the toString method.

package com.mylifes1110.test;

import com.mylifes1110.java.Season;

public class Seaso1Test {
    public static void main(String[] args) {
        Season1 spring = Season.SPRING;
        System.out.println(spring);                     //SPRING
        System.out.println(spring.getSeasonName());     / / in the spring}}Copy the code

Here I put the printed result in a comment following the print statement. Why do we find SPRING printed without overriding the toString method? This should be analyzed from our inheritance relationship. If we inherit from the base Object class, the toString method is not overridden to print the address of the Object. Then we can conclude that the parent of an enum enum class is not Object. So who is its parent? We can get the parent class from the object as follows:

System.out.println(Season.class.getSuperclass());		//class java.lang.Enum
Copy the code

Again, the answer is in a comment at the end of the code. We found that it inherits the Enum class by default. So, we’ll see what methods are written in this class later.

Enum The use of common methods

6.1 All methods in Enum

All the methods in the Enum class are listed in a table!

The return value methods describe
String name() Gets the name of the enumerator
static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) Gets an enumerator that specifies the enumerator name and type
String[] values() Gets all the values of the enumerator
int compareTo(E o) Compares the order of this enumeration with the specified objects
int hashCode() Gets the hash value of an enumerator
int ordinal() Gets the ordinal number of an enumerator (the first enumerator position is 0)
String toString() Returns the enumerator name
Class<E> getDeclaringClass() Gets the class object of an enumeration member

6.2 the name and toString

The name method and the toString method are pretty simple. Name () is the string name that gets the enumerator based on that enumerator. The same String method is used to get the String name of the enumeration member. The name method is final and cannot be overridden, whereas toString can be overridden. Here we also use the seasonal example to demonstrate, printing the result and putting it in a comment at the end of the code, as follows:

System.out.println(Season.SUMMER.name());			//SUMMER
System.out.println(Season.SUMMER.toString());		//SUMMER
Copy the code

6.3 the valueOf

The purpose of this method is to pass in a string and then convert it to the corresponding enumerator. The string passed in here must match the name of the enumerated member being defined and be strictly case sensitive. If the string passed in does not find its corresponding enumerator object, an exception is thrown. As follows:

System.out.println(Season.valueOf("WINTER"));			//WINTER
System.out.println(Season.valueOf("WIN"));				//java.lang.IllegalArgumentException
Copy the code

6.4 values

The values method has an S in its name, plus its return value is an array of strings. So we can conclude that its purpose is to get all the values of the enumeration member and store them as an array.

Season[] seasons = Season.values();
for (Season season : seasons) {
    System.out.print(season + "");
}
Copy the code

The result is:

SPRING SUMMER AUTUMN WINTER 
Copy the code

6.5 the ordinal

This method gets the ordinal number of an enumerator whose first position is 0. In fact, you can think of it as an index in an array. The first element position in the array also starts at 0. Let’s print it out and see what it looks like, as follows:

// Gets the order of the specified enumeration members
System.out.println(Season.SUMMER.ordinal());

// Get the order of all members
Season[] seasons = Season.values();
for (Season s : seasons) {
    System.out.println(s + "- >" + s.ordinal());
}
Copy the code

The result is:

The source code returns a value of type int starting at 0. The maximum value is the maximum value of the int range. As follows:

6.6 compareTo

The compareTo method is believed to be familiar. That’s what it’s for. But what does it compare in an enumerated class? The compareTo method actually compares the ordinal number of two enumerators and returns the result of subtracting the order.

First, we need to know that the ordinal number of SUMMER is 1, and the ordinal number of WINTER is 3. When the former is used to compare the latter, the printed result is the difference between the former and the latter, which is 1-3=-2

System.out.println(Season.SUMMER.compareTo(Season.WINTER));			/ / - 2
Copy the code

What’s the source code for it? Let’s go inside and check it out.

All the previous operations determine whether the two sides of the comparison are an enumerated class and throw an exception if they are not. If it is an enumerated class, the ordinal is subtracted and returned.

Advanced features of Java enumeration

7.1 constant

We know that constants are public static final. With the advent of enumerations, we were able to put related constants in an enumeration container, and the advantage of using enumerations is that they provide many convenient methods.

Example:

public enum Season {
    SPRING, SUMMER, AUTUMN, WINTER
}
Copy the code

7.2 switch statement

What types of switch statements do you know? Switch statements support the following types:

  • Basic data types: byte, short, CHAR, int
  • Wrapper data types: Byte, Short, Character, and Integer
  • Enumeration type: Enum
  • String type: String (jdk7+ start support)

How is the use of enumerated classes and switch statements implemented? How does enumeration facilitate switch statements? Take a look.

package com.mylifes1110.java;

public class WeekTest {
    public static void main(String[] args) {
        Week week = Week.MONDAY;
        switch (week) {
            case MONDAY:
                System.out.println("Monday");
                break;
            case TUESDAY:
                System.out.println("Tuesday");
                break;
            case WEDNESDAY:
                System.out.println("Wednesday");
                break;
            case THURSDAY:
                System.out.println("Thursday");
                break;
            case FRIDAY:
                System.out.println("Friday");
                break;
            case SATURDAY:
                System.out.println("Saturday");
                break;
            case SUNDAY:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("null"); }}}enum Week {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Copy the code

7.3 Enumeration defines multiple parameters and methods

As I explained in 5.2, we can define enumerations not only with multiple parameters, but also with other common methods. The use of common methods depends on the situation, so I won’t go into details here.

package com.mylifes1110.java;

public enum Season {
    SPRING("Spring"),
    SUMMER("Summer"),
    AUTUMN("Autumn"),
    WINTER("Winter");

    private final String seasonName;
    
    public static String getName(int index) {  
        for (Season s : Season.values()) {  
            if (c.getIndex() == index) {  
                returnc.name; }}return null;  
    }

    Season1(String seasonName) {
        this.seasonName = seasonName;
    }

    public String getSeasonName(a) {
        returnseasonName; }}Copy the code

7.4 Enumeration classes implement interfaces

Although enumerated classes cannot inherit, they can implement interfaces. Here is an implementation.

First, create an interface.

package com.mylifes1110.inter;

public interface Show {
    void show(a);
}
Copy the code

Second, let our four Seasons enumeration class implement the interface override method.

package com.mylifes1110.java;

import com.mylifes1110.inter.Show;

public enum Season implements Show {
    SPRING("Spring"),
    SUMMER("Summer"),
    AUTUMN("Autumn"),
    WINTER("Winter");

    private final String seasonName;

    Season1(String seasonName) {
        this.seasonName = seasonName;
    }

    public String getSeasonName(a) {
        return seasonName;
    }

    @Override
    public void show(a) {
        System.out.println("Yearning for all seasons like spring."); }}Copy the code

Finally, we can call the show method when we use each enumeration class, and print the result of “Wishing for spring”.

Season.WINTER.show();				// Yearning for four seasons like spring
Copy the code

You and I are smart enough to see that we call the show method the same regardless of which enumerator we use. So, after we implement the interface, we can override the method as follows:

package com.mylifes1110.java;

import com.mylifes1110.inter.Show;

public enum Season1 implements Show {
    SPRING("Spring") {
        @Override
        public void show(a) {
            System.out.println("Spring is the season for outings.");
        }
    },
    SUMMER("Summer") {
        @Override
        public void show(a) {
            System.out.println("Summer is a hot season. I want to eat popsicles.");
        }
    },
    AUTUMN("Autumn") {
        @Override
        public void show(a) {
            System.out.println("Autumn is still cool.");
        }
    },
    WINTER("Winter") {
        @Override
        public void show(a) {
            System.out.println("The snow is good in winter, but it's a little cold."); }};private final String seasonName;

    Season1(String seasonName) {
        this.seasonName = seasonName;
    }

    public String getSeasonName(a) {
        returnseasonName; }}Copy the code

We add {} to the end of the enumerator, and the overridden method can be written in each enumerator, thus touching all of the above limitations. Which enumerator object we use to call the show method is different. Isn’t that NICE?

7.5 Using Interfaces to Enumerate Categories

To classify enumerations using interfaces, we need to create an interface container containing multiple enumerations that the interface container contains, and then implement each enumeration class into the interface, so as to achieve the classification of enumerations. The code looks like this, with the printed result in a comment following the code:

package com.mylifes1110.inter;

public interface Weeks {
    / / working days
    enum WorkingDay implements Weeks {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
    }

    / / double cease day
    enum Weekend implements Weeks {
        SATURDAY, SUNDAY
    }
}

class WeeksTest {
    public static void main(String[] args) {
        System.out.print("Weekends:");
        for (Weeks.Weekend weekend : Weeks.Weekend.values()) {
            System.out.print(weekend + "");        // SATURDAY SUNDAY
        }

        / / a newline
        System.out.println();

        System.out.print("Working day:");
        for (Weeks.WorkingDay workingDay : Weeks.WorkingDay.values()) {
            System.out.print(workingDay + "");     // Weekdays: MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY
        }

        / / a newline
        System.out.println();

        Weeks.WorkingDay friday = Weeks.WorkingDay.FRIDAY;
        System.out.println("Friday:" + friday);      // FRIDAY: FRIDAY}}Copy the code

A collection of eight enumerated classes

8.1 enumsets collection

With respect to a Set, we know that the elements in the Set are not repeated. The methods are as follows:

The return value methods describe
static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) Creates an enumeration set containing all elements of the specified element type.
EnumSet<E> clone() Returns a set.
static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) Creates a set whose element type is the same as the specified enumeration set (the new set contains enumerators not included in the original set)
static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) Creates an enumeration set whose element type is the same as the specified enumeration set (the new set contains the same enumerators as the original set)
static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> s) Creates an enumeration set initialized from the specified collection
static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) Creates an empty enumerated set with the specified element type
static <E extends Enum<E>> EnumSet<E> range(E from, E to) Creates an enumeration set that initially contains all elements in the range defined by the two specified endpoints.
static <E extends Enum<E>> EnumSet<E> of Creates an enumeration set that initially contains the specified element. Note: Multiple elements can be specified, so I’m not listing the parameters here
8.1.1 allOf

The allOf method requires us to pass in an enumerated class object, and it generates a Set of enumerated members from that enumerated class object.

// Create a Set containing all enumerated elements of Week
EnumSet<Week> weeks = EnumSet.allOf(Week.class);
System.out.println(weeks);              //[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]

// Prints the elements in the Set
for (Week week1 : weeks) {
    System.out.print(week1 + "");      //MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY
}
Copy the code
8.1.2 clone

The clone method gives the same result as printing the enumeration’s Set Set directly!

// Return a Set
System.out.println(weeks.clone());      //[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
Copy the code
8.1.3 range

As detailed above, enumerations are ordered numbers, and enumerators in an enumeration class are ordered from left to right. So we can use the range method to create a Set that specifies the endpoints of the enumerator. That is, we need to pass in the start and end of the enumerator to create a Set that has the range enumerator. As follows:

// Creates an enumeration set that initially contains all elements in the range defined by the two specified endpoints.
System.out.println(EnumSet.range(Week.MONDAY, Week.FRIDAY));        //[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
Copy the code
8.1.4 complementOf

This method is a bit special in that it creates a new Set from EnumSet. The enumerator in the new Set is equivalent to the negation of the enumerator in the old Set.

Let’s simulate a scenario where the current Week enumeration class has seven enumerators from Monday to Sunday. We used the range method to create a Set Set (S1) from Monday to Friday. Then I would use the imitation of method to generate a new Set (S2) according to S1. Finally, I printed S2 to view the elements in the Set, just Saturday and Sunday.

Note: If our old Set occupies all the enumerators in the enumeration class, the elements in the new Set are printed as an empty Set using the imitation of method, i.e. [].

// Create a set whose element type is the same as the specified enumeration set (the new set contains enumerators not included in the original set)
EnumSet<Week> weeks1 = EnumSet.complementOf(weeks);
System.out.println(weeks1);             / / []

EnumSet<Week> range = EnumSet.range(Week.MONDAY, Week.FRIDAY);
EnumSet<Week> weeks3 = EnumSet.complementOf(range);
System.out.println(weeks3);    			//[SATURDAY, SUNDAY]
Copy the code
8.1.5 copyOf

The copyOf method is the opposite of imitation of; it creates a new Set. The enumerators in the new Set are the same as the enumerators in the old Set, which is equivalent to Copy. If you understand the imitation of method, that method also does not challenge you. Here I use the copyOf method to copy a copyOf weeks, one enumerator at a time.

Note: The copyOf method also has a way to copy the Connection collection to create a Set, and the connection collection must store enumerators.

// Create an enumeration set whose element type is the same as the specified enumeration set.
EnumSet<Week> weeks2 = EnumSet.copyOf(weeks);
System.out.println(weeks2);             //[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
Copy the code
// Copy the collection of hashSets that store enumeration members
Set set = new HashSet();
set.add(Week.MONDAY);
EnumSet set1 = EnumSet.copyOf(set);
System.out.println(set1);		//[MONDAY]
Copy the code
8.1.6 of

The of method gives us the optional convenience of picking any enumerator to be a member of the Set.

// Create an enumeration set that initially contains the specified element.
System.out.println(EnumSet.of(Week.MONDAY,Week.FRIDAY));            //[MONDAY, FRIDAY]
Copy the code
8.1.7 noneOf

Pass in an enumerated class object to create an empty Set

EnumSet<Week> noneOf = EnumSet.noneOf(Week.class);
System.out.println(noneOf);                     / / []
Copy the code

8.2 EnumMap collection

8.2.1 EnumMap Method list of the set

The Map set, we know, is made up of keys and values. The efficiency of EnumMap is higher than that of HashMap.

There is nothing special about the use of the EnumMap collection that is consistent with HashMap. As for the methods of the EnumMap collection, I’ll list them here.

The return value methods describe
void clear() Remove all mappings.
EnumMap<K,V> clone() Return the EnumMap collection.
boolean containsKey(Object key) If this key is included, true is returned
boolean containsValue(Object value) Contains one or more keys mapped to the specified value, returns true
Set<Map.Entry<K,V>> entrySet() Returns a Set of mapping key-value relationships
boolean equals(Object o) Compare the equality between objects and maps
V get(Object key) Gets the value of the specified key map, or null if none is present
Set<K> keySet() Returns a Set of all keys
V put(K key, V value) Stores the specified key value in the EnumMap collection
void putAll(Map<? extends K,? extends V> m) Store all key-value pairs in a collection
V remove(Object key) If a mapping exists, remove it
int size() Returns the number of mappings that exist
Collection<V> values() Returns a Collection of values contained in this map
8.2.2 Basic Usage of EnumMap

Since the EnumMap collection is basically similar to the HashMap collection, I’ll show you where the basic usage differs from the HashMap collection.

The EnumMap collection is the object that we new out, and the created object needs to pass in an enumerated class object to return a Map collection. Map sets are key-value pairs, so when we write generics for EnumMap sets, we write them as required. If we want the key to be an enumeration type, we write it. If an enumerated class is required for a value, write the value in the generic to an enumerated class. Key/value pairs are required to be enumerations and that’s OK, we’ll just write the required enumeration class when we write generics. Except that you need to specify enumeration classes to create and store objects, this is basically the same as a HashMap.

The key of the generic type is the Week enumerator, and the value is an Integer. This means that when we put (store key-value pairs), the key needs to store the enumerator from the Week enumerator, and the value needs to store the Integer value.

EnumMap<Week, Integer> map = new EnumMap<>(Week.class);
map.put(Week.MONDAY, 1);
map.put(Week.THURSDAY, 4);
System.out.println(map);			//{MONDAY=1, THURSDAY=4}
Copy the code