枚举的典型场景

实际应用中,枚举经常会有关联的实例变量和方法。

举个栗子,假设Size的枚举值可能有关联的缩写和中文名称,可能需要静态方法根据缩写返回对应的枚举值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public enum Size {
SMALL("S","小号"),
MEDIUM("M","中号"),
LARGE("L","大号");

private String abbr;
private String title;

private Size(String abbr,String title) {
this.abbr = abbr;
this.title = title;
}

public String getAbbr() {
return abbr;
}

public String getTitle() {
return title;
}

//根据abbr返回枚举值,比如输入M返回MEDIUM
public static Size fromAbbr(String abbr) {
for (Size size : Size.values()) {
if (size.getAbbr().equals(abbr)) {
return size;
}
}
return null;
}
}

枚举值的定义需要放在最上面,枚举值写完之后,要以分号结尾,然后才能写其他代码

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2021 Silver Shaded
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信