Enum application --------- enum

Definition of enumeration

In mathematical and computer science theory, enumeration of a set is a program that lists all members of some finite sequence set, or a count of a specific type of object. These two types often (but not always) overlap. It is a collection of named integer constants. Enumeration is very common in daily life. For example, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY are enumerations.

How to implement enumeration in java language

All of us who have studied java know that java is an object-oriented language. Coincidentally, there are some objects that can be summarized into food in the world, such as seasons, weeks, months, etc,

For simplicity, take Zhou as an example - as a demonstration of enumeration classes;

import java.util.Scanner;

final class Week {
    private final String WEEKNAME;//Season name
    private final String WEEKDESC;//Seasonal description

    //Define the construction method --- it cannot be modified by the outside world
    private Week(String WEEKNAME, String WEEKDESC) {
        this.WEEKNAME = WEEKNAME;
        this.WEEKDESC = WEEKDESC;
    }

  

    public String getWEEKDESC() {
        return WEEKDESC;
    }

    public static Week getMON() {
        return MON;
    }

    public static Week getTUE() {
        return TUE;
    }

    public static Week getWED() {
        return WED;
    }

    public static Week getTHIR() {
        return THIR;
    }

    public static Week getFRI() {
        return FRI;
    }

    public static Week getSAT() {
        return SAT;
    }

    public static Week getSUN() {
        return SUN;
    }

    //Define instance - Monday to Sunday
    private final static Week MON = new Week("Monday", "weekdays");
    private final static Week TUE = new Week("Tuesday", "Valentine's Day");
    private final static Week WED = new Week("Wednesday", "weekdays");
    private final static Week THIR = new Week("Thursday", "weekdays");
    private final static Week FRI = new Week("Friday", "weekdays");
    private final static Week SAT = new Week("Saturday", "Rest Day");
    private final static Week SUN = new Week("Sunday", "Rest Day");
}

public class meiju {
    public static void main(String[] args) {
        System.out.println("Please enter the information to query---");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                System.out.println(Week.getMON().getWEEKDESC());
                break;
            case 2:
                System.out.println(Week.getTUE().getWEEKDESC());
                break;
            case 3:
                System.out.println(Week.getWED().getWEEKDESC());
                break;
            case 4:
                System.out.println(Week.getTHIR().getWEEKDESC());
                break;
            case 5:
                System.out.println(Week.getFRI().getWEEKDESC());
                break;
            case 6:
                System.out.println(Week.getSAT().getWEEKDESC());
                break;
            case 7:
                System.out.println(Week.getSUN().getWEEKDESC());
            default:
                System.out.println("clasp the moon in the Ninth Heaven");

                sc.close();
        }
    }

}

It looks cumbersome, doesn't it, so in jdk1 After 5, the enumeration class appears

Replace the above code with an enumeration class to see the difference----

Implementation of java enumeration class


import java.util.Scanner;

enum Week {
//Define instance - Monday to Sunday
MON ("Monday", "weekdays"),
TUE("Tuesday", "Valentine's Day"),
 WED  ("Wednesday", "weekdays"),
THIR("Thursday", "weekdays"),
 FRI ("Friday", "weekdays"),
SAT ("Saturday", "Rest Day"),
 SUN ("Sunday", "Rest Day");

private final String WEEKNAME;//Season name
    private final String WEEKDESC;//Seasonal description

    //Define the construction method --- it cannot be modified by the outside world
    private Week(String WEEKNAME, String WEEKDESC) {
        this.WEEKNAME = WEEKNAME;
        this.WEEKDESC = WEEKDESC;
    }

    public String getWEEKDESC() {
        return WEEKDESC;
    }

    public static Week getMON() {
        return MON;
    }

    public static Week getTUE() {
        return TUE;
    }

    public static Week getWED() {
        return WED;
    }

    public static Week getTHIR() {
        return THIR;
    }

    public static Week getFRI() {
        return FRI;
    }

    public static Week getSAT() {
        return SAT;
    }

    public static Week getSUN() {
        return SUN;
    }



}

public class meiju {
    public static void main(String[] args) {
        System.out.println("Please enter the information to query---");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                System.out.println(Week.getMON().getWEEKDESC());
                break;
            case 2:
                System.out.println(Week.getTUE().getWEEKDESC());
                break;
            case 3:
                System.out.println(Week.getWED().getWEEKDESC());
                break;
            case 4:
                System.out.println(Week.getTHIR().getWEEKDESC());
                break;
            case 5:
                System.out.println(Week.getFRI().getWEEKDESC());
                break;
            case 6:
                System.out.println(Week.getSAT().getWEEKDESC());
                break;
            case 7:
                System.out.println(Week.getSUN().getWEEKDESC());
            default:
                System.out.println("clasp the moon in the Ninth Heaven");

                sc.close();
        }
    }

}

It can be found that
1. The instantiated object is placed at the beginning of the enumeration class;
2. The enumeration object does not need the form of new, but directly write the construction method of the object;
3. The enumeration objects are separated by commas, and the last object is a semicolon;

enum classes can define either parametric or nonparametric constructs - this is the same as ordinary classes, but there are some differences in instantiation;

For example –

The enum class inherits Java Lang.enum class

Enumerate some other methods in the class

 Week mon = Week.valueOf("MON");//Returns the name of the current enumeration class
        System.out.println(mon);
        Week[] values = Week.values();//Get all enumerated objects in the form of an array
        for (Week w:values
             ) {
            System.out.println(w);
        }

Other ways to implement enumeration ----- enumeration keyword

package org_chwenyu_learn;
public class Meiju {
enum Week {
Sun. Mon.Tue.Wed.Thu.Fri.Sat }
// Enumeration type syntax format -- enum enumeration name {element 1. Element 2};
// When enumerating, be sure to enumerate all elements.
public static void main(String[] args) {

// Enum name object name = enum name Enumeration element
Week c1 = Week.Sat;
switch (c1) {
case Sat: System.out.println("Today is Saturday"); break;
default: { System.out.println("Go to school today"); } }
Week[]allWeek=Week.values();//Traversal enumeration object
for (Week aWeek:allWeek) { System.out.print(aWeek+"."); }
System.out.println("****************************");
System.out.println(c1.getDeclaringClass());//Returns the enumeration name where c1 is located
System.out.println(c1.hashcode());//Returns the hash code of the enumeration constant
System.out.println(c1.name());//Returns the name of the enumeration constant (declared at definition time)
System.out.println(c1.ordinal());//Returns the position of an enumeration constant in an enumeration declaration Ordinal numbers start at 0
System.out.println(c1.toString());//Returns the name of an enumeration constant.}

The difference between enum class and enum keyword

Using keywords to define enumeration actually inherits Enum class;
Class Enum<E extends Enum>
java.lang.Enum

In the main method, the process enumeration class cannot be public

Enumeration and interface

Since enumeration can be a class, you can implement the interface like an ordinary class;

package enumTest;

interface DescribeSeason {
    void desc();
}
enum WEEKEND implements DescribeSeason {
    //Define instance - Monday to Sunday
    MON {
        @Override
        public void desc() {
            System.out.println("Monday");
        }
    },

    TUE() {
        @Override
        public void desc() {

            System.out.println("Tuesday");
        }
    },

    WED {
        @Override
        public void desc() {
            System.out.println("Wednesday");
        }
    },

    THIR {
        @Override
        public void desc() {
            System.out.println("Thursday");
        }
    },
    FRI {
        @Override
        public void desc() {
            System.out.println("Friday");
        }
    },
    SAT {
        @Override
        public void desc() {
            System.out.println("Saturday");
        }
    },
    SUN {
        @Override
        public void desc() {
            System.out.println("Sunday");
        }
    };
}

be careful:

  • The constructor of an enumeration class cannot be declared in public because the constructor of an enumeration cannot be called externally

  • Once the enumeration construction is defined, the enumeration construction method should be used

Enumeration and interface class set support for enumeration

EnumMap class

Basic information of EnumMap -

public class EnumMap<K extends Enum,V> extends AbstractMap<K,V>
implements Serializable, Cloneable a specialized Map implementation used with enumeration type keys. All keys in an enumeration Map must come from a single enumeration type explicitly or implicitly specified when the Map was created. Enumeration maps are internally represented as arrays.

1. When instantiating EnumMap, specify the enumeration type - that is, import the enumerated class information

Code Demonstration -

public class MeijuLeiji {
    public static void main(String[] args) {
        EnumMap<WEEKEND,Integer> we=new EnumMap<WEEKEND, Integer>(WEEKEND.class);//Specifies the enumeration type
        we.put(WEEKEND.MON,1);
        we.put(WEEKEND.TUE,2);
        we.put(WEEKEND.WED,3);
        we.put(WEEKEND.THIR,4);
        we.put(WEEKEND.FRI,5);
        we.put(WEEKEND.SAT,6);
        we.put(WEEKEND.SUN,7);
        Set<Map.Entry<WEEKEND, Integer>> entries = we.entrySet();
        for (Map.Entry e:entries
             ) {
            System.out.println(e.getValue());
        }
 EnumMap<WEEKEND, Integer> clone = we.clone();//Returns a shallow copy of the EnumMap
        System.out.println(clone.size());//Return EnumMap class set size - 7
        clone.putAll(we);//Add another class set to the class set;
        System.out.println(clone.size());//Returns the size of EnumMap class set --- because there are duplicate values, the size is still 7
    }
}

Summary -

1. Like most other class sets, enummap is asynchronous and thread unsafe Pay attention to external synchronization when accessing multiple threads;

2. If no such object exists, collections should be used synchronizedMap(java.util.Map<K,
5> ) method "wrap" map. This is best done at creation time to prevent accidental asynchronous access

 Map<EnumKey, V> mapEnum
         = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...)); 

Enumset class

Look at the picture first----

Basic information of Enumset class -

public abstract class EnumSet<E extends Enum>
extends AbstractSet implements Cloneable, Serializable

A specialized Set implementation is used with enumeration types. All elements in the enumeration Set must come from a single enumeration type specified explicitly or implicitly when the collection is created.

The enumeration set is internally represented as a bit vector. This representation is very compact and efficient. The space and time performance of this class should be good enough to be used as a high-quality, type safe alternative to the "bit flag" based on traditional int. Even batch operations such as containsAll and retainAll should run quickly

Enumset is an abstract class, which can only be instantiated through subclasses or methods; Therefore, the error prompt in the figure above will appear;

public class MeijuLeiji {
    public static void main(String[] args) {
    //Creates an enumeration set containing all elements in the specified element type. 
              EnumSet<WEEKEND> weekends= EnumSet.allOf(WEEKEND.class);
        boolean add = weekends.add(WEEKEND.TUE);
        weekends.add(WEEKEND.FRI);
        weekends.add(WEEKEND.SUN);//Add element
        System.out.println(weekends.size());//Class set size
        EnumSet<WEEKEND> clone = weekends.clone();//Clone class set
        clone.remove(WEEKEND.FRI);//remove
        System.out.println(clone.spliterator());
        
        //Creates an enumeration set that initially contains the specified element.
EnumSet<WEEKEND>weekendEnumSet=EnumSet.of(WEEKEND.MON,WEEKEND.TUE,WEEKEND.THIR);
        Iterator<WEEKEND> iterator = weekendEnumSet.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    System.out.println("---------------------------------------------");
        //Creates an enumeration set with the same element type as the specified enumeration set, initially containing all elements of this type, which are not included in the specified collection.
        //Generally speaking, this method is to eliminate all the data in the weekendEnumSet enumeration after weekendEnumSet
        EnumSet<WEEKEND>weekends1=EnumSet.complementOf(weekendEnumSet);
        Iterator<WEEKEND> iterator1 = weekends1.iterator();
        while(iterator1.hasNext()) {
            System.out.println(iterator1.next());
        }
    }
}

Summary -

1. Enumset, like most other class sets, is asynchronous and thread unsafe Pay attention to external synchronization when accessing multiple threads;

2. If no such object exists, collections should be used The synchronizedset (Java. Util. Set) method "wraps" the map. This is best done at creation time to prevent accidental asynchronous access

  Set<MyEnum> s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class)); 

Main applications of enumeration class

1. If there is only a limited number of data, you can use enumeration class to specify the input range of data-----
For example, gender, login status and other countable data of some instance objects;

public enum Gender {
    male,female;
}
class Person{
    String name;
    Gender sex;

    public Person(String name, Gender sex) {
        this.name = name;
        this.sex = sex;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(Gender sex) {
        this.sex = sex;
    }
}

In this way, only two kinds of data can be selected when setting gender - male and female

2. Switch supports enumeration;

import java.util.Scanner;
import static enumTest.Gender.male;

/**
 * @author : Gavin
 * @date: 2021/8/24 - 08 - 24 - 11:27
 * @Description: enumTest
 * @version: 1.0
 */
public class Test {
    public static void main(String[] args) {
        Person per = new Person("Zhang San", male);//Static import
        Person per1 = new Person("Li Ergou", Gender.female);
        String sexs = null;
        Scanner sc = new Scanner(System.in);
        sexs = sc.next();
        Gender sex = Gender.valueOf(sexs);
        switch (sex) {//switch support for int, short, byte, enum and string types
            case male:
                System.out.println("Zhang San");
                break;
            case female:
                System.out.println("Li Ergou");
                break;
        }
        sc.close();
    }
}

Added by sepodati on Tue, 21 Dec 2021 09:41:52 +0200