第六章:枚举和注解。ITEM30:用enum代替int常量。&ITEM32:用EnumSet代替位域。&ITEM33:用EnumMap代替序数索引。...

 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     }

 

转载于:https://my.oschina.net/u/726229/blog/310075

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值