Introduction to java -- Enumeration

Introduction to java -- Enumeration

concept

enumeration is a new feature introduced in JDK 1.5

grammar

public enum Color{
    //Add public static final Color by default
    RED,GREEN,BLUE;
}

essence

Enumeration is a restricted class and has its own methods. When you create your own enum class, this class inherits from Java lang.Enum

be careful:

Enum is a restricted class that inherits enum by default

The first row of the enumeration must define an object of the enumeration type

Enumeration type objects are added by default: public static final

Enumeration does not inherit explicit class (custom enumeration class inherits Enum by default, Enum inherits Object by default)

Enumeration classes cannot be inherited

Enumeration can construct methods, member methods, static methods and abstract methods

Enumerations can implement interfaces

When there is no method defined in the enumeration, you can add comma, semicolon or nothing after the last object

advantage:

Enhance code readability

Enumeration type can directly interact with the database

switch statement advantages

Compilation advantages: (when compiling enumeration classes, constant values are not compiled into the code. Even if the constant values are changed, the classes that reference constants will not be affected)

Organize constants and manage them uniformly

Remove the equal judgment. Since the constant value address is unique, you can directly compare the two values through "= =" using enumeration, and the performance will be improved

Case: write a season class. There are only four objects in the class: spring, summer, autumn and winter

package com.dream.enum01;

public class Season {
	//Construct the object by yourself and modify it final ly. The object cannot be modified
	public static final Season spring = new Season("spring", "Recovery of all things");
	public static final Season summer = new Season("summer", "sweat profusely");
	public static final Season autumn = new Season("autumn", "fresh autumn weather");
	public static final Season winter = new Season("winter", "The cold wind is biting");

	private String name;
	private String info;
	
    //The construction method is privatized and does not allow the outside world to create new objects
	private Season() {
	}
	//The construction method is privatized and does not allow the outside world to create new objects
	private Season(String name, String info) {
		this.name = name;
		this.info = info;
	}

	public String getName() {
		return name;
	}

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

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	@Override
	public String toString() {
		return "Season [name=" + name + ", info=" + info + "]";
	}
}
package com.dream.enum01;

public class Test01 {
	
	public static void main(String[] args) {
		/**
		 * Enumeration import:
		 * Write the Season class, which has only four objects (spring, summer, autumn, winter)
		 */
		
		System.out.println(Season.spring);
		System.out.println(Season.summer);
		System.out.println(Season.autumn);
		System.out.println(Season.winter);
	}

}

Season [name=spring, info=Recovery of all things]
Season [name=summer, info=sweat profusely]
Season [name=autumn, info=fresh autumn weather]
Season [name=winter, info=The cold wind is biting]

Using enumeration classes

package com.dream.enum02;

//Underlying implementation: public class season extensions enum
public enum Season{

	//Default: public static final Season
	spring("spring","The spring rain is continuous"),
	summer("summer","Sweating profusely"),
	autumn("autumn","Fruitful"),
	winter("winter","Silver and plain");
	
	private String name;
	private String info;
	
	private Season() {
	}

	private Season(String name, String info) {
		this.name = name;
		this.info = info;
	}

	public String getName() {
		return name;
	}

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

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}
	
	@Override
	public String toString() {
		return name + " -- " + info;
	}
}

package com.dream.enum02;

public class Test01 {
	
	public static void main(String[] args) {
		/**
		 * Enumeration import:
		 * Write the Season class, which has only four objects (spring, summer, autumn, winter)
		 * 
		 * Use enumeration to address this requirement
		 */
		
		System.out.println(Season.spring);
		System.out.println(Season.summer);
		System.out.println(Season.autumn);
		System.out.println(Season.winter);
	}

}
spring -- The spring rain is continuous
 summer -- Sweating profusely
 autumn -- Fruitful
 winter -- Silver and plain

Common methods of enumeration

package com.dream.enum03;

public class Test01 {

	public static void main(String[] args) {
		/**
		 * Knowledge points: common methods of enumeration
		 */
		
		//Gets the object in the enumeration class through a string
		Season season1 = Enum.valueOf(Season.class, "spring");
		System.out.println(season1);
		
		//Get all the objects in the Season enumeration class
		Season[] values = Season.values();
		for (Season season : values) {
			System.out.println(season);
		}
		
		//Gets the object in the enumeration class through a string
		Season season2 = Season.valueOf("summer");
		System.out.println(season2);
		
		//Gets the name of the enumeration object
		String name = season2.name();
		System.out.println(name);
		
		//Gets the bytecode file object of the Season enumeration class
		Class<Season> c = season2.getDeclaringClass();
		System.out.println(c);
	}
}
spring -- The spring rain is continuous
 spring -- The spring rain is continuous
 summer -- Sweating profusely
 autumn -- Fruitful
 winter -- Silver and plain
 summer -- Sweating profusely
summer
class com.dream.enum03.Season

Case: state machine

package com.dream.enum04;

import java.util.Scanner;

public class Test01 {

	public static void main(String[] args) {
		/**
		 * Enumerating cases - state machines
		 */

		Scanner scan = new Scanner(System.in);

		System.out.println("Please enter the signal light: RED, YELLOW, GREEN");
		String next = scan.next();

		Signal signal = Signal.valueOf(next);

		switch (signal) {
		case RED:
			System.out.println("Stop at red light");
			break;
		case YELLOW:
			System.out.println("Yellow light, please pay attention");
			break;
		case GREEN:
			System.out.println("pass at a green light");
			break;
		}

		scan.close();
	}
}

enum Signal{RED, YELLOW, GREEN}
Please enter the signal light: RED, YELLOW, GREEN
RED
 Stop at red light

Case: error code

public enum ErrorCodeEn {
	
	Ok(1,"success"),ERROR_A(2,"error A"),ERROR_B(3,"error B");
	
	private int code;//Status code
	private String info;//State description
	
	ErrorCodeEn(){}
	
	ErrorCodeEn(int code,String info){
		this.code = code;
		this.info = info;
	}

	public int getCode() {
		return code;
	}

	public String getInfo() {
		return info;
	}
}

Organization enumeration

Meaning: enumerations of similar types can be organized through interfaces or classes (but they are generally organized by interfaces)

as a result of:

The Java interface will automatically add the public static modifier to the enum type at compile time;

Java classes will automatically add static modifier to enum type at compile time;

That is, organize enum in the class. If you don't modify it to public, you can only access it in this package.

public interface IErrorCode {

	enum LoginErrorCodeEn implements INumberEnum{

		OK(1,"Login succeeded"),ERROR_A(-1,"Verification code error"),ERROR_B(-2,"Password error"),ERROR_C(-3,"User logged in");

		private int code;
		private String description;

		LoginErrorCodeEn(int code,String description){
			this.code = code;
			this.description = description;
		}

		@Override
		public int getCode() {
			return code;
		}
		@Override
		public String getDescription() {
			return description;
		}
	}

	enum RigsterErrorCodeEn implements INumberEnum{

		OK(1,"login was successful"),ERROR_A(-1,"Account already exists");

		private int code;
		private String description;

		RigsterErrorCodeEn(int code,String description){
			this.code = code;
			this.description = description;
		}

		@Override
		public int getCode() {
			return code;
		}
		@Override
		public String getDescription() {
			return description;
		}
	}

}

interface INumberEnum {
	int getCode();
	String getDescription();
}

strategy enum

Advantages: this enumeration classifies enumeration constants by enumerating nested enumerations.

Although this approach is not as concise as the switch statement, it is more secure and flexible.

package com.Xu.MyEnum;


public enum CalculatingArea {//Calculated area
	triangle(Area.TRIANGLE),//triangle
	rectangular(Area.RECTANGULAR);//rectangle
	
	private final Area area;
	
	CalculatingArea(Area area) {
		this.area = area;
	}
	
	double getCalculatingArea(int length,int high) {
		return area.count(length,high);
	}

	private enum Area{

		TRIANGLE{//triangle
			@Override
			double count(int length,int high) {//Rewrite calculation method
				return length*high/2;
			}
		},
		
		RECTANGULAR{//rectangle
			@Override
			double count(int length,int high) {//Rewrite calculation method
				return length*high;
			}
		};
		
		abstract double count(int length,int high);//The area calculation methods of triangles and rectangles are different, and they are rewritten with abstract classes
	}

}
package com.Xu.MyEnum;

public class Test {
	
	public static void main(String[] args) {
		
		double d1 = CalculatingArea.triangle.getCalculatingArea(4, 5);//Triangular area
		double d2 = CalculatingArea.rectangular.getCalculatingArea(4, 5);//Rectangular area

		System.out.println("Triangle area:"+d1);
		System.out.println("Rectangular area:"+d2);
	}
}
10.0
20.0

Enumeration tool classes - EnumSet and EnumMap

Java provides two tool classes that facilitate the operation of enum - EnumSet and EnumMap.

EnumSet: a high-performance implementation of enum types. It requires that the enumeration constants put into it must belong to the same enumeration type.
EnumMap: a Map implementation tailored to enumeration types. Although other Map implementations are used (such as HashMap) can also complete the enumeration type instance to value mapping, but using EnumMap is more efficient because it can only receive instances of the same enumeration type as key values. Because the number of enumeration type instances is relatively fixed and limited, EnumMap uses arrays to store the values corresponding to enumeration types. This makes EnumMap very efficient.

public class EnumTest {
	public static void main(String[] args) {
		
		//Use of EnumSet
        //Extract all objects in the Signal enumeration into the Set collection
		EnumSet<Signal> signalSet = EnumSet.allOf(Signal.class);
		for (Enum<Signal> en : signalSet) {
			System.out.println(en);
		}
		
		//Use of EnumMap
		EnumMap<Signal,Object> enumMap = new EnumMap<>(Signal.class);
		enumMap.put(Signal.RED, "red light");
		enumMap.put(Signal.YELLOW, "Yellow lamp");
		enumMap.put(Signal.GREEN, "green light");
        //Extract all mapping objects into the Set
		Set<Entry<Signal, Object>> entrySet = enumMap.entrySet();
		for (Entry<Signal, Object> entry : entrySet) {
			Signal key = entry.getKey();
			Object value = entry.getValue();
			System.out.println(key + " -- " + value);
		}
	}
}
enum Signal{RED, YELLOW, GREEN}

Keywords: Java Programming Eclipse enum

Added by dotwebbie on Thu, 30 Dec 2021 05:50:51 +0200