Java Enumeration Class Use

Keywords: jvm Java Apache

Articles Catalogue

I. Examples of Several Enumeration Classes

1. Simplest Enumeration

	enum Nuber {
	    One, Two
	}// enum's grammatical structure is different from class's, but after compiling by JVM compiler, it produces a class file. The class file is decompiled to see that it actually generates a class that inherits java.lang.enum<E>. Each class has a default parametric constructor, so you can leave it out here.

2. General Enumeration Class Usage

	public enum Person {
	    // enum instances must be written at the top of the enumeration class, or compile errors
	    WORKER(0, "Worker"), STUDENT(1, "Student");// If you want to define a method, you need to add one after the last enum instance.
	
	    // encapsulation
	    private int index;
	    private String desc;
	
	    // There must be a constructor that corresponds to the structure of the enum instance
	    private Person(int index, String desc) {// The constructor access modifier here does not differ in accessibility whether it is declared private or not, but for clarity, it is recommended to add
	        this.index = index;
	        this.desc = desc;
	    }
	}

3. Use enumeration in switch

	package com.wsjia.ms.controller;
	import org.apache.commons.lang.StringUtils;
	
	public enum FruitEnum {
	
		APPLE("Apple", "apple"),
		BANNER("Banana", "banner");
	
		private String name;
		private String type;
	
		FruitEnum(String name, String type) {
			this.name = name;
			this.type = type;
		}
	
		public String getName() {
			return name;
		}
	
		public String getType() {
			return type;
		}
	
		public static FruitEnum getByType(String type) {
			if (StringUtils.isNotBlank(type)) {
				for (FruitEnum entity : values()) {
					if (entity.getType().equalsIgnoreCase(type.trim())) {
						return entity;
					}
				}
			}
			return null;
		}
	
		public static FruitEnum getByName(String name) {
			if (StringUtils.isNotBlank(name)) {
				for (FruitEnum entity : values()) {
					if (entity.getName().equalsIgnoreCase(name.trim())) {
						return entity;
					}
				}
			}
			return null;
		}
	
	}
-------------------------------------------------------------------------------------------

	FruitEnum fruitEnum = FruitEnum.getByType("apple");
	switch (fruitEnum) {
		case APPLE:
		case BANNER:
			System.out.println(fruitEnum.getName());
			break;
	}

Enumeration Class Method

  1. values() method, which returns an array of enum instances in which elements strictly maintain the order in which they are declared in enum
  2. ordinal(), returns the order in which the Enum instance is declared in enum (starting from 0)
  3. The compareTo() method compares the order differences declared in enum
  4. equals() is equivalent to==
  5. name() is equivalent to toString(), returning the name of the enumerated instance

Posted by dujed on Thu, 10 Oct 2019 01:15:30 -0700