Java Enumeration Class Use
Keywords:
jvm
Java
Apache
I. Examples of Several Enumeration Classes
1. Simplest Enumeration
enum Nuber {
One, Two
}
2. General Enumeration Class Usage
public enum Person {
WORKER(0, "Worker"), STUDENT(1, "Student");
private int index;
private String desc;
private Person(int index, String desc) {
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
- values() method, which returns an array of enum instances in which elements strictly maintain the order in which they are declared in enum
- ordinal(), returns the order in which the Enum instance is declared in enum (starting from 0)
- The compareTo() method compares the order differences declared in enum
- equals() is equivalent to==
- name() is equivalent to toString(), returning the name of the enumerated instance
Posted by dujed on Thu, 10 Oct 2019 01:15:30 -0700