
什么是枚举?
枚举是一个特殊的class,继承了java.lang.Enum类 ,存储了一组有序的常量,这些常量都是枚举的实例。
/**
* @Author: Juncheng
* @Date: 2021/4/12 16:33
* @Description:
*/
public enum Demo1Enum {
MA,SUN,DAI
}
/**
* @Author: Juncheng
* @Date: 2021/4/12 16:33
* @Description:
*/
public enum Demo2Enum {
RED("红", 1),
BLUE("蓝", 2);
private String colour;
private int type;
Demo2Enum(String colour, int type) {
this.colour = colour;
this.type = type;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
枚举的使用
//获取枚举,返回的是枚举的实例
Demo1Enum ma = Demo1Enum.MA;
//结果:MA
String name = ma.name();
Demo2Enum red = Demo2Enum.RED;
//结果:红
String colour = red.getColour();
-
values(),以数组形式返回枚举类型的所有成员
Demo1Enum[] values = Demo1Enum.values();
-
valueOf(),将字符串转换为枚举实例
Demo1Enum ma = Demo1Enum.valueOf("MA");
-
compareTo(),比较两个枚举成员在定义时的顺序,返回int类型
/*
数值代表距离,0代表两个成员在相同的位置,
正值代表方法中参数在调用该方法的枚举对象位置之前,
负值代表方法中参数在调用该方法的枚举对象位置之后
*/
int i = Demo1Enum.MA.compareTo(Demo1Enum.DAI);
-
ordinal(),获取枚举成员的索引位置,索引从0开始
int ordinal = Demo1Enum.MA.ordinal();