参考:https://www.cnblogs.com/sunxucool/archive/2012/12/03/2800021.html
一、简单枚举
示例:
// 当枚举类只有一个属性时,这个枚举类是单例的
public enum Weather {
winter,
spring,
summer,
fall
}
1. 枚举转化成int
int i = Weather.winter.ordinal(); // => 0
2.int转化成枚举
Weather b= Weather.values()[0];
3.枚举转化成String
String winter = Weather.winter.name(); // => winter
4. String转化成枚举
Weather weather = Weather.valueOf("spring");
二、带参数枚举
示例:
public enum BusinessType {
USER_BUSINESS,
ORDER_BUSINESS
}
public enum BusinessEnum {
User(1, BusinessType.USER_BUSINESS),
Order(2, BusinessType.ORDER_BUSINESS);
private int type;
private BusinessType businessType;
private BusinessEnum(int type, BusinessType businessType) {
this.type = type;
this.businessType = businessType;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public BusinessType getBusinessType() {
return businessType;
}
public void setBusinessType(BusinessType businessType) {
this.businessType = businessType;
}
public static BusinessEnum getEnumByType(int type) {
for (BusinessEnum bt : values()) {
if (bt.type == type) {
return bt;
}
}
return null;
}
}
1. int 转化成枚举
BusinessEnum business1 = BusinessEnum.getEnumByType(1); // => User
BusinessType type1 = business1.getBusinessType(); // => USER_BUSINESS
示例:
public enum Lamtern {
RED(200), YELLOW(30), GREEN(200);
int time;
private Lamtern(int time) {
this.time = time;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public static Lamtern getLamtern(int time) {
for (Lamtern c : Lamtern.values()) {
if (c.getTime() == time) {
return c;
}
}
return null;
}
}
1.int转化成枚举
Lamtern lamtern = Lamtern.getLamtern(200);