1 package com.twoslow.cha6;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 public enum Operation {
7
8 PLUS("+") {
9 @Override
10 double apply(double x, double y) {
11 return x + y;
12 }
13 },MINUS("-") {
14 @Override
15 double apply(double x, double y) {
16 return x - y;
17 }
18 },TIMES("*") {
19 @Override
20 double apply(double x, double y) {
21 return x * y;
22 }
23 },DIVIDE("/"){
24 @Override
25 double apply(double x, double y) {
26 return x / y;
27 }
28 };
29
30 private static final Map<String, Operation> stringToEnum = new HashMap<String, Operation>() ;
31
32 //将定制的字符串表示法变回相应的枚举。
33 static {
34 for(Operation op : values()) {
35 stringToEnum.put(op.toString(), op) ;
36 }
37 }
38
39 public static Operation fromString(String symbol) {
40 return stringToEnum.get(symbol) ;
41 }
42
43 private final String symbol ;
44
45 Operation(String symbol) {
46 this.symbol = symbol ;
47 }
48
49 public String toString() {
50 return symbol ;
51 }
52
53 abstract double apply(double x ,double y) ;
54 }
1 public class Text {
2 public enum Style { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH }
3 public void applyStyles(Set<Style> styles) { ... }
4
5 }
6 //使用方式如下:
7 text.applyStyles(EnumSet.of(Style.BOLD,Style.ITALIC));
在一个花园里面有很多的植物,它们被分成 3 类,分别是一年生(ANNUAL)、多年生(PERENNIAL)和两年生(BIENNIAL),正好对应着 Herb.Type 中的枚举值。
现在我们需要做的是遍历花园中的每一个植物,并将这些植物分为 3 类,最后再将分类后的植物分类打印出来:
1 package com.twoslow.cha6;
2
3 public class Herb {
4 public enum Type { ANNUAL, PERENNIAL, BIENNIAL }
5 private final String name;
6 private final Type type;
7
8 Herb(String name, Type type) {
9 this.name = name;
10 this.type = type;
11 }
12
13 @Override
14 public String toString() {
15 return name;
16 }
17 }
1 public static void main(String[] args) {
2 Herb[] garden = ...;
3 Map<Herb.Type, Set<Herb>> herbsByType =new EnumMap<Herb.Type, Set<Herb>>(Herb.Type.class);
4
5 for (Herb.Type t : Herb.Type.values()) {
6 herbsByType.put(t, new HashSet<Herb>());
7 }
8 for (Herb h : garden) {
9 herbsByType.get(h.type).add(h);
10 }
11 System.out.println(herbsByType);
12 }