欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中的枚举类型详细介绍

程序员文章站 2023-01-10 17:53:26
枚举中有values方法用于按照枚举定义的顺序生成一个数组,可以用来历遍。我们自定义的枚举类都是继承自java.lang.enum,拥有一下实例中的功能: 复制代码 代码如...
枚举中有values方法用于按照枚举定义的顺序生成一个数组,可以用来历遍。我们自定义的枚举类都是继承自java.lang.enum,拥有一下实例中的功能:
复制代码 代码如下:

//: enumerated/enumclass.java
// capabilities of the enum class
import static net.mindview.util.print.*;
enum shrubbery { ground, crawling, hanging }
public class enumclass {
  public static void main(string[] args) {
    for(shrubbery s : shrubbery.values()) {
      print(s + " ordinal: " + s.ordinal());
      printnb(s.compareto(shrubbery.crawling) + " ");
      printnb(s.equals(shrubbery.crawling) + " ");
      print(s == shrubbery.crawling);
      print(s.getdeclaringclass());
      print(s.name());
      print("----------------------");
    }
    // produce an enum value from a string name:
    for(string s : "hanging crawling ground".split(" ")) {
      shrubbery shrub = enum.valueof(shrubbery.class, s);
      print(shrub);
    }
  }
} /* output:
ground ordinal: 0
-1 false false
class shrubbery
joshua bloch was extremely helpful in developing this chapter.
ground
----------------------
crawling ordinal: 1
true true
class shrubbery
crawling
----------------------
hanging ordinal: 2
false false
class shrubbery
hanging
----------------------
hanging
crawling
ground
*///:~

我们还可以使用静态的枚举引用:
复制代码 代码如下:

//: enumerated/spiciness.java
package enumerated;
public enum spiciness {not, mild, medium, hot, flaming} ///:~
//: enumerated/burrito.java
package enumerated;
import static enumerated.spiciness.*;
public class burrito {
  spiciness degree;
  public burrito(spiciness degree) { this.degree = degree;}
  public string tostring() { return "burrito is "+ degree;}
  public static void main(string[] args) {
    system.out.println(new burrito(not));
    system.out.println(new burrito(medium));
    system.out.println(new burrito(hot));
  }
} /* output:
burrito is not
burrito is medium
burrito is hot
*///:~

向枚举添加方法
除了不能被继承之外,枚举可以当作一般的类来看待,这意味着可以向枚举添加方法,还可以在枚举中定义main方法:
复制代码 代码如下:

//: enumerated/ozwitch.java
// the witches in the land of oz.
import static net.mindview.util.print.*;
public enum ozwitch {
  // instances must be defined first, before methods:
  west("miss gulch, aka the wicked witch of the west"),north("glinda, the good witch of the north"),east("wicked witch of the east, wearer of the ruby " + "slippers, crushed by dorothy's house"),south("good by inference, but missing");
  private string description;
  // constructor must be package or private access:
  private ozwitch(string description) {
    this.description = description;
  }
  public string getdescription() { return description; }
  public static void main(string[] args) {
    for(ozwitch witch : ozwitch.values())
      print(witch + ": " + witch.getdescription());
  }
} /* output:
west: miss gulch, aka the wicked witch of the west
north: glinda, the good witch of the north
east: wicked witch of the east, wearer of the ruby slippers, crushed by dorothy's house
south: good by inference, but missing
*///:~

复制代码 代码如下:

//: enumerated/spaceship.java
public enum spaceship {
  scout, cargo, transport, cruiser, battleship, mothership;
  public string tostring() {
    string id = name();
    string lower = id.substring(1).tolowercase();
    return id.charat(0) + lower;
  }
  public static void main(string[] args) {
    for(spaceship s : values()) {
      system.out.println(s);
    }
  }
} /* output:
scout
cargo
transport
cruiser
battleship
mothership
*///:~

switch语句中的枚举
  枚举的一种重要作用就是在switch语句中,通常switch语句仅对整型值起作用,但是枚举中有内置的整型顺序,因此实例的顺序可以通过某种方法获得,因此enums就可以在switch语句中使用:
复制代码 代码如下:

//: enumerated/trafficlight.java
// enums in switch statements.
import static net.mindview.util.print.*;
// define an enum type:
enum signal { green, yellow, red, }
  public class trafficlight {
    signal color = signal.red;
    public void change() {
    switch(color) {
      // note that you don't have to say signal.red
      // in the case statement:
      case red: color = signal.green;
            break;
      case green: color = signal.yellow;
            break;
      case yellow: color = signal.red;
            break;
    }
  }
  public string tostring() {
    return "the traffic light is " + color;
  }
  public static void main(string[] args) {
    trafficlight t = new trafficlight();
    for(int i = 0; i < 7; i++) {
      print(t);
      t.change();
    }
  }
} /* output:
the traffic light is red
the traffic light is green
the traffic light is yellow
the traffic light is red
the traffic light is green
the traffic light is yellow
the traffic light is red
*///:~

values()的秘密
  虽然我们之前使用了values方法,但是如果查看enum,我们并没有发现values方法,那么是不是还有其他隐藏的方法呢?我们可以通过一个简单的反射代码来查看一下:
复制代码 代码如下:

//: enumerated/reflection.java
// analyzing enums using reflection.
import java.lang.reflect.*;
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.print.*;
enum explore { here, there }
public class reflection {
  public static set<string> analyze(class<?> enumclass) {
    print("----- analyzing " + enumclass + " -----");
    print("interfaces:");
    for(type t : enumclass.getgenericinterfaces())
      print(t);
    print("base: " + enumclass.getsuperclass());
    print("methods: ");
    set<string> methods = new treeset<string>();
    for(method m : enumclass.getmethods())
      methods.add(m.getname());
    print(methods);
    return methods;
  }
  public static void main(string[] args) {
    set<string> exploremethods = analyze(explore.class);
    set<string> enummethods = analyze(enum.class);
    print("explore.containsall(enum)? " +
    exploremethods.containsall(enummethods));
    printnb("explore.removeall(enum): ");
    exploremethods.removeall(enummethods);
    print(exploremethods);
    // decompile the code for the enum:
    osexecute.command("javap explore");
  }
} /* output:
----- analyzing class explore -----
interfaces:
base: class java.lang.enum
methods:
[compareto, equals, getclass, getdeclaringclass, hashcode, name, notify, notifyall, ordinal, tostring, valueof, values, wait]
----- analyzing class java.lang.enum -----
interfaces:
java.lang.comparable<e>
interface java.io.serializable
base: class java.lang.object
methods:
[compareto, equals, getclass, getdeclaringclass, hashcode, name, notify, notifyall, ordinal, tostring, valueof, wait]
explore.containsall(enum)? true
explore.removeall(enum): [values]
compiled from "reflection.java"
final class explore extends java.lang.enum{
public static final explore here;
public static final explore there;
public static final explore[] values();
public static explore valueof(java.lang.string);
static {};
}
*///:~

我们可以看到values方法是被编译器添加的。valueof方法也是在创建枚举的时候由编译器添加的,但是在enum类中也有一个valueof方法,但是这个方法有两个参数,而由编译器添加的valueof方法只有一个参数。枚举被编译器解释为final,因此枚举不能被继承。因为values方法是被编译器添加的静态方法,因此如果你将枚举上塑造型到enum的时候,values方法将会不可用,但是在class中有getenumconstants方法,因此虽然values方法在enum中不可用,但是还是可以通过class对象获取枚举的实例:
复制代码 代码如下:

//: enumerated/upcastenum.java
// no values() method if you upcast an enum
enum search { hither, yon }
public class upcastenum {
  public static void main(string[] args) {
    search[] vals = search.values();
    enum e = search.hither; // upcast
    // e.values(); // no values() in enum
    for(enum en : e.getclass().getenumconstants())
      system.out.println(en);
  }
} /* output:
hither
yon
*///:~

实现而不继承
  因为我们定义的枚举类型都继承自java.lang.enum,而且java又不支持多重继承,因此不同通过继承创建枚举,但是可以通过继承一个或多个接口创建枚举:
复制代码 代码如下:

//: enumerated/cartoons/enumimplementation.java
// an enum can implement an interface
package enumerated.cartoons;
import java.util.*;
import net.mindview.util.*;
enum cartooncharacter implements generator<cartooncharacter> {
  slappy, spanky, punchy, silly, bouncy, nutty, bob;
  private random rand = new random(47);
  public cartooncharacter next() {
    return values()[rand.nextint(values().length)];
  }
}
public class enumimplementation {
  public static <t> void printnext(generator<t> rg) {
    system.out.print(rg.next() + ", ");
  }
  public static void main(string[] args) {
    // choose any instance:
    cartooncharacter cc = cartooncharacter.bob;
    for(int i = 0; i < 10; i++)
      printnext(cc);
  }
} /* output:
bob, punchy, bob, spanky, nutty, punchy, slappy, nutty, nutty, slappy,
*///:~

随机选取
  后面我们很多例子中都会用到从枚举实例中随机选取对象,我们创建一个公用类来实现:
复制代码 代码如下:

//: net/mindview/util/enums.java
package net.mindview.util;
import java.util.*;
public class enums {
  private static random rand = new random(47);
  public static <t extends enum<t>> t random(class<t> ec) {
    return random(ec.getenumconstants());
  }
  public static <t> t random(t[] values) {
    return values[rand.nextint(values.length)];
  }
} ///:~

复制代码 代码如下:

//: enumerated/randomtest.java
import net.mindview.util.*;
enum activity { sitting, lying, standing, hopping, running, dodging, jumping, falling, flying }
public class randomtest {
  public static void main(string[] args) {
    for(int i = 0; i < 20; i++)
      system.out.print(enums.random(activity.class) + " ");
  }
} /* output:
standing flying running standing running standing lying dodging sitting running hopping hopping hopping running standing lying falling running flying lying
*///:~

使用接口进行组织
  枚举不能被继承,这一点有时候会给我们造成不方便,因为有些时候我们想要通过继承来扩展枚举的数量,有些时候我们需要对枚举进行分组。对于后者我们可以通过在接口内定义分组的枚举,然后在通过继承自这个接口来创建枚举,如下我们有不同的食物类需要创建为枚举,但是我们又需要将每个种类定义为food的类型,如下:
复制代码 代码如下:

//: enumerated/menu/food.java
// subcategorization of enums within interfaces.
package enumerated.menu;
public interface food {enum appetizer implements food {salad, soup, spring_rolls;}
  enum maincourse implements food {lasagne, burrito, pad_thai,lentils, hummous, vindaloo;}
  enum dessert implements food {tiramisu, gelato, black_forest_cake,fruit, creme_caramel;}
  enum coffee implements food {black_coffee, decaf_coffee, espresso,latte, cappuccino, tea, herb_tea;}
} ///:~

因为每个枚举都定义为接口的实现,因此每个枚举都是food类型,如下:
复制代码 代码如下:

//: enumerated/menu/typeoffood.java
package enumerated.menu;
import static enumerated.menu.food.*;
public class typeoffood {
  public static void main(string[] args) {
    food food = appetizer.salad;
    food = maincourse.lasagne;
    food = dessert.gelato;
    food = coffee.cappuccino;
  }
} ///:~

但是接口不能像枚举一样操作多种类型,因此如果你需要一个枚举的枚举,那么你可以在一个枚举里面封装每个枚举类型的一个实例:
复制代码 代码如下:

//: enumerated/menu/course.java
package enumerated.menu;
import net.mindview.util.*;
public enum course {
  appetizer(food.appetizer.class),maincourse(food.maincourse.class),dessert(food.dessert.class),coffee(food.coffee.class);
  private food[] values;
  private course(class<? extends food> kind) {
    values = kind.getenumconstants();
  }
  public food randomselection() {
    return enums.random(values);
  }
} ///:~

每个枚举使用了class对象作为对应的构造器参数,我们就可以从这个参数里面使用getenumconstants来获得枚举实例,这个实例可以用在randomselection方法中生成随机的餐点:
复制代码 代码如下:

//: enumerated/menu/meal.java
package enumerated.menu;
public class meal {
  public static void main(string[] args) {
    for(int i = 0; i < 5; i++) {
      for(course course : course.values()) {
        food food = course.randomselection();
        system.out.println(food);
      }
      system.out.println("---");
    }
  }
} /* output:
spring_rolls
vindaloo
fruit
decaf_coffee
---
soup
vindaloo
fruit
tea
---
salad
burrito
fruit
tea
---
salad
burrito
creme_caramel
latte
---
soup
burrito
tiramisu
espresso
---
*///:~

下面是一种更加紧凑的实现方法:
复制代码 代码如下:

//: enumerated/securitycategory.java
// more succinct subcategorization of enums.
import net.mindview.util.*;
enum securitycategory {
  stock(security.stock.class), bond(security.bond.class);
  security[] values;
  securitycategory(class<? extends security> kind) {
    values = kind.getenumconstants();
  }
  interface security {
    enum stock implements security { short, long, margin }
    enum bond implements security { municipal, junk }
  }
  public security randomselection() {
    return enums.random(values);
  }
  public static void main(string[] args) {
    for(int i = 0; i < 10; i++) {
      securitycategory category = enums.random(securitycategory.class);
      system.out.println(category + ": " +
      category.randomselection());
    }
  }
} /* output:
bond: municipal
bond: municipal
stock: margin
stock: margin
bond: junk
stock: short
stock: long
stock: long
bond: municipal
bond: junk
*///:~

复制代码 代码如下:

//: enumerated/menu/meal2.java
package enumerated.menu;
import net.mindview.util.*;
public enum meal2 {
  appetizer(food.appetizer.class),maincourse(food.maincourse.class),dessert(food.dessert.class),coffee(food.coffee.class);
  private food[] values;
  private meal2(class<? extends food> kind) {
    values = kind.getenumconstants();
  }
  public interface food {
    enum appetizer implements food {salad, soup, spring_rolls;}
    enum maincourse implements food {lasagne, burrito, pad_thai,lentils, hummous, vindaloo;}
    enum dessert implements food {tiramisu, gelato, black_forest_cake,fruit, creme_caramel;}
    enum coffee implements food {black_coffee, decaf_coffee, espresso,latte, cappuccino, tea, herb_tea;}
  }
  public food randomselection() {
    return enums.random(values);
  }
  public static void main(string[] args) {
    for(int i = 0; i < 5; i++) {
      for(meal2 meal : meal2.values()) {
        food food = meal.randomselection();
        system.out.println(food);
      }
      system.out.println("---");
    }
  }
} /* same output as meal.java *///:~

使用enumset而不是标志位
  在java se5中添加了enumset来将枚举和set组合用于替换基于整型的位标志。位标志通常用来指示某种信息的开关,但是在代码中是对位进行操作而不是有意义的概念,因此不容易理解。enumset的效率比位标志要快,在内部使用long性表示一个位向量,然后就可以使用更加概念化的语言来表示某个位的开关,而不用担心效率。enumset中的元素必须来自同一个枚举,下面定义一个报警器位置的枚举:
复制代码 代码如下:

//: enumerated/alarmpoints.java
package enumerated;
public enum alarmpoints {stair1, stair2, lobby, office1, office2, office3,office4, bathroom, utility, kitchen} ///:~

然后使用enumset类跟踪报警的状态:
复制代码 代码如下:

//: enumerated/enumsets.java
// operations on enumsets
package enumerated;
import java.util.*;
import static enumerated.alarmpoints.*;
import static net.mindview.util.print.*;
public class enumsets {
  public static void main(string[] args) {
    enumset<alarmpoints> points = enumset.noneof(alarmpoints.class); // empty set
    points.add(bathroom);
    print(points);
    points.addall(enumset.of(stair1, stair2, kitchen));
    print(points);
    points = enumset.allof(alarmpoints.class);
    points.removeall(enumset.of(stair1, stair2, kitchen));
    print(points);
    points.removeall(enumset.range(office1, office4));
    print(points);
    points = enumset.complementof(points);
    print(points);
  }
} /* output:
[bathroom]
[stair1, stair2, bathroom, kitchen]
[lobby, office1, office2, office3, office4, bathroom, utility]
[lobby, bathroom, utility]
[stair1, stair2, office1, office2, office3, office4, kitchen]
*///:~

enumset是建立在long型上的,有64位,那么如果我们的枚举类型超过了这个数字呢?
复制代码 代码如下:

//: enumerated/bigenumset.java
import java.util.*;
public class bigenumset {
  enum big { a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21,a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32,
a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43,a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54,a55, a56, a57, a58, a59, a60, a61, a62, a63, a64, a65,
a66, a67, a68, a69, a70, a71, a72, a73, a74, a75 }
  public static void main(string[] args) {
    enumset<big> bigenumset = enumset.allof(big.class);
    system.out.println(bigenumset);
  }
} /* output:
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, a61, a62, a63, a64, a65, a66, a67, a68, a69, a70, a71, a72, a73, a74, a75]
*///:~

我们可以看到程序正常运行,那么很有可能是内部又添加了一个long型来帮助容纳枚举类型
使用enummap
  enummap是一种特殊类型的map,他的键的值只能是同一个枚举中的类型,因为这一点在内部可以通过数组来实现enummap,效率非常高。
复制代码 代码如下:

//: enumerated/enummaps.java
// basics of enummaps.
package enumerated;
import java.util.*;
import static enumerated.alarmpoints.*;
import static net.mindview.util.print.*;
interface command { void action(); }
public class enummaps {
  public static void main(string[] args) {
    enummap<alarmpoints,command> em = new enummap<alarmpoints,command>(alarmpoints.class);
    em.put(kitchen, new command() {
      public void action() { print("kitchen fire!"); }
    });
    em.put(bathroom, new command() {
      public void action() { print("bathroom alert!"); }
    });
    for(map.entry<alarmpoints,command> e : em.entryset()) {
      printnb(e.getkey() + ": ");
      e.getvalue().action();
    }
    try { // if there's no value for a particular key:
      em.get(utility).action();
    } catch(exception e) {
      print(e);
    }
  }
} /* output:
bathroom: bathroom alert!
kitchen: kitchen fire!
java.lang.nullpointerexception
*///:~

特定常量方法
  java的枚举有一个非常有趣的特性,那就是可以为每一个枚举实例定义不同的行为,为了实现这一点,我们定义一个或者多个抽象方法作为枚举的一部分,然后为每个枚举实例定义方法:
复制代码 代码如下:

//: enumerated/constantspecificmethod.java
import java.util.*;
import java.text.*;
public enum constantspecificmethod {
  date_time {string getinfo() {return dateformat.getdateinstance().format(new date());}},
  classpath {string getinfo() {return system.getenv("classpath");}},
version {string getinfo() {return system.getproperty("java.version");}};
  abstract string getinfo();
  public static void main(string[] args) {
    for(constantspecificmethod csm : values())
      system.out.println(csm.getinfo());
  }
} /* (execute to see output) *///:~

上面的代码卡起来似乎是每个枚举元素都是不同的元素,而所有的元素都继承自constantspecificmethod基类,但是我们不能真的这样理解,因为我们不能将枚举元素当作类型来看待:
复制代码 代码如下:

//: enumerated/notclasses.java
// {exec: javap -c likeclasses}
import static net.mindview.util.print.*;
enum likeclasses {winken { void behavior() { print("behavior1"); } },blinken { void behavior() { print("behavior2"); } },nod { void behavior() { print("behavior3"); } };
  abstract void behavior();
}
public class notclasses {
  // void f1(likeclasses.winken instance) {} // nope
} /* output:
compiled from "notclasses.java"
abstract class likeclasses extends java.lang.enum{
public static final likeclasses winken;
public static final likeclasses blinken;
public static final likeclasses nod;
...
*///:~

考虑另外一个例子,有一个洗车的菜单,客户根据不同的菜单选择不同的服务,可以使用特定常量方法来将菜单与服务相关联,使用enumset来维护客户的选择,如下:
复制代码 代码如下:

//: enumerated/carwash.java
import java.util.*;
import static net.mindview.util.print.*;
public class carwash {
  public enum cycle {underbody {void action() { print("spraying the underbody"); }},
wheelwash {void action() { print("washing the wheels"); }},
         prewash {void action() { print("loosening the dirt"); }},
         basic {void action() { print("the basic wash"); }},
         hotwax {void action() { print("applying hot wax"); }},
         rinse {void action() { print("rinsing"); }},
         blowdry {void action() { print("blowing dry"); }};
         abstract void action();
  }
  enumset<cycle> cycles = enumset.of(cycle.basic, cycle.rinse);
  public void add(cycle cycle) { cycles.add(cycle); }
  public void washcar() {
    for(cycle c : cycles)
      c.action();
  }
  public string tostring() { return cycles.tostring(); }
  public static void main(string[] args) {
    carwash wash = new carwash();
    print(wash);
    wash.washcar();
    // order of addition is unimportant:
    wash.add(cycle.blowdry);
    wash.add(cycle.blowdry); // duplicates ignored
    wash.add(cycle.rinse);
    wash.add(cycle.hotwax);
    print(wash);
    wash.washcar();
  }
} /* output:
[basic, rinse]
the basic wash
rinsing
[basic, hotwax, rinse, blowdry]
the basic wash
applying hot wax
rinsing
blowing dry
*///:~

我们还可以对默认的特定常量方法进行重写,而不是使用继承抽象方法,如下:
复制代码 代码如下:

//: enumerated/overrideconstantspecific.java
import static net.mindview.util.print.*;
public enum overrideconstantspecific {
  nut, bolt,washer {void f() { print("overridden method"); }};
  void f() { print("default behavior"); }
  public static void main(string[] args) {
    for(overrideconstantspecific ocs : values()) {
      printnb(ocs + ": ");
      ocs.f();
    }
  }
} /* output:
nut: default behavior
bolt: default behavior
washer: overridden method
*///:~

有些时候我们希望对特定的请求在链条中进行传递,知道链条中的某个对象能够处理请求,使用特定常量方法可以很轻松的实现,如下是一个处理邮件的实例:
复制代码 代码如下:

//: enumerated/postoffice.java
// modeling a post office.
enumerated types 743
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.print.*;
class mail {
  // the no's lower the probability of random selection:
  enum generaldelivery {yes,no1,no2,no3,no4,no5}
  enum scannability {unscannable,yes1,yes2,yes3,yes4}
  enum readability {illegible,yes1,yes2,yes3,yes4}
  enum address {incorrect,ok1,ok2,ok3,ok4,ok5,ok6}
  enum returnaddress {missing,ok1,ok2,ok3,ok4,ok5}
  generaldelivery generaldelivery;
  scannability scannability;
  readability readability;
  address address;
  returnaddress returnaddress;
  static long counter = 0;
  long id = counter++;
  public string tostring() { return "mail " + id; }
  public string details() {
  return tostring() + ", general delivery: " + generaldelivery + ", address scanability: " + scannability + ", address readability: " + readability +
", address address: " + address + ", return address: " + returnaddress;
  }
  // generate test mail:
  public static mail randommail() {
    mail m = new mail();
    m.generaldelivery= enums.random(generaldelivery.class);
    m.scannability = enums.random(scannability.class);
    m.readability = enums.random(readability.class);
    m.address = enums.random(address.class);
    m.returnaddress = enums.random(returnaddress.class);
    return m;
  }
  public static iterable<mail> generator(final int count) {
    return new iterable<mail>() {
      int n = count;
      public iterator<mail> iterator() {
        return new iterator<mail>() {
          public boolean hasnext() { return n-- > 0; }
          public mail next() { return randommail(); }
          public void remove() { // not implemented
            throw new unsupportedoperationexception();
          }
        };
      }
    };
  }
}
public class postoffice {
  enum mailhandler {
    general_delivery {
      boolean handle(mail m) {
        switch(m.generaldelivery) {
          case yes:
            print("using general delivery for " + m);
            return true;
          default: return false;
        }
      }
    },
    machine_scan {
      boolean handle(mail m) {
        switch(m.scannability) {
          case unscannable: return false;
          default:
            switch(m.address) {
              case incorrect: return false;
              default:
                print("delivering "+ m + " automatically");
              return true;
            }
        }
      }
    },
    visual_inspection {
      boolean handle(mail m) {
        switch(m.readability) {
          case illegible: return false;
          default:
            switch(m.address) {
              case incorrect: return false;
              default:
                print("delivering " + m + " normally");
              return true;
            }
        }
      }
    },
    return_to_sender {
      boolean handle(mail m) {
        switch(m.returnaddress) {
          case missing: return false;
          default:
            print("returning " + m + " to sender");
          return true;
        }
      }
    };
    abstract boolean handle(mail m);
  }
  static void handle(mail m) {
    for(mailhandler handler : mailhandler.values())
      if(handler.handle(m))
        return;
    print(m + " is a dead letter");
  }
  public static void main(string[] args) {
    for(mail mail : mail.generator(10)) {
      print(mail.details());
      handle(mail);
      print("*****");
    }
  }
} /* output:
mail 0, general delivery: no2, address scanability: unscannable, address readability: yes3, address address: ok1, return address: ok1
delivering mail 0 normally
*****
mail 1, general delivery: no5, address scanability: yes3, address readability: illegible, address address: ok5, return address: ok1
delivering mail 1 automatically
*****
mail 2, general delivery: yes, address scanability: yes3, address readability: yes1, address address: ok1, return address: ok5
using general delivery for mail 2
*****
mail 3, general delivery: no4, address scanability: yes3, address readability: yes1, address address: incorrect, return address: ok4
returning mail 3 to sender
*****
mail 4, general delivery: no4, address scanability: unscannable, address readability: yes1, address address: incorrect, return address: ok2
returning mail 4 to sender
*****
mail 5, general delivery: no3, address scanability: yes1, address readability: illegible, address address: ok4, return address: ok2
delivering mail 5 automatically
*****
mail 6, general delivery: yes, address scanability: yes4, address readability: illegible, address address: ok4, return address: ok4
using general delivery for mail 6
*****
mail 7, general delivery: yes, address scanability: yes3, address readability: yes4, address address: ok2, return address: missing
using general delivery for mail 7
*****
mail 8, general delivery: no3, address scanability: yes1, address readability: yes3, address address: incorrect, return address: missing
mail 8 is a dead letter
*****
mail 9, general delivery: no1, address scanability: unscannable, address readability: yes2, address address: ok1, return address: ok4
delivering mail 9 normally
*****
*///:~

枚举类型还是创建状态机的理想类型,一个状态机可以根据输入在有限个状态之间移动,然后在满足某种状态之后结束工作,另外每个状态都会有相应的输出,一个售货机器是一个典型的状态机的实例,我们在枚举内定义不同的输入:
复制代码 代码如下:

//: enumerated/input.java
package enumerated;
import java.util.*;
public enum input {
  nickel(5), dime(10), quarter(25), dollar(100),toothpaste(200), chips(75), soda(100), soap(50),abort_transaction {
    public int amount() { // disallow
      throw new runtimeexception("abort.amount()");
    }
  },
  stop { // this must be the last instance.
    public int amount() { // disallow
      throw new runtimeexception("shut_down.amount()");
    }
  };
  int value; // in cents
  input(int value) { this.value = value; }
  input() {}
  int amount() { return value; }; // in cents
  static random rand = new random(47);
  public static input randomselection() {
    // don't include stop:
    return values()[rand.nextint(values().length - 1)];
  }
} ///:~

vendingmachine用来对输入进行相应,首先通过category枚举归类输入,然后使用switch语句:
复制代码 代码如下:

//: enumerated/vendingmachine.java
// {args: vendingmachineinput.txt}
package enumerated;
import java.util.*;
import net.mindview.util.*;
import static enumerated.input.*;
import static net.mindview.util.print.*;
enum category {
  money(nickel, dime, quarter, dollar),item_selection(toothpaste, chips, soda, soap),quit_transaction(abort_transaction),shut_down(stop);
  private input[] values;
  category(input... types) { values = types; }
  private static enummap<input,category> categories = new enummap<input,category>(input.class);
  static {
    for(category c : category.class.getenumconstants())
      for(input type : c.values)
        categories.put(type, c);
  }
  public static category categorize(input input) {
    return categories.get(input);
  }
}
public class vendingmachine {
  private static state state = state.resting;
  private static int amount = 0;
  private static input selection = null;
  enum stateduration { transient } // tagging enum
  enum state {
    resting {
      void next(input input) {
        switch(category.categorize(input)) {
          case money:
            amount += input.amount();
            state = adding_money;
            break;
          case shut_down:
            state = terminal;
          default:
        }
      }
    },
    adding_money {
      void next(input input) {
        switch(category.categorize(input)) {
          case money:
            amount += input.amount();
            break;
          case item_selection:
            selection = input;
            if(amount < selection.amount())
              print("insufficient money for " + selection);
            else state = dispensing;
              break;
          case quit_transaction:
            state = giving_change;
            break;
          case shut_down:
            state = terminal;
            default:
        }
      }
    },
    dispensing(stateduration.transient) {
      void next() {
        print("here is your " + selection);
        amount -= selection.amount();
        state = giving_change;
      }
    },
    giving_change(stateduration.transient) {
      void next() {
        if(amount > 0) {
          print("your change: " + amount);
          amount = 0;
        }
        state = resting;
      }
    },
    terminal { void output() { print("halted"); } };
    private boolean istransient = false;
    state() {}
    state(stateduration trans) { istransient = true; }
    void next(input input) {
      throw new runtimeexception("only call " + "next(input input) for non-transient states");
    }
    void next() {
      throw new runtimeexception("only call next() for " + "stateduration.transient states");
    }
    void output() { print(amount); }
  }
  static void run(generator<input> gen) {
    while(state != state.terminal) {
      state.next(gen.next());
      while(state.istransient)
        state.next();
      state.output();
    }
  }
  public static void main(string[] args) {
    generator<input> gen = new randominputgenerator();
    if(args.length == 1)
      gen = new fileinputgenerator(args[0]);
    run(gen);
  }
}
// for a basic sanity check:
class randominputgenerator implements generator<input> {
  public input next() { return input.randomselection(); }
}
// create inputs from a file of ‘;'-separated strings:
class fileinputgenerator implements generator<input> {
  private iterator<string> input;
  public fileinputgenerator(string filename) {
    input = new textfile(filename, ";").iterator();
  }
  public input next() {
    if(!input.hasnext())
      return null;
    return enum.valueof(input.class, input.next().trim());
  }
} /* output:
here is your chips
here is your toothpaste
your change: 35
insufficient money for soda

insufficient money for soda
your change: 75
halted
*///:~

下面是用来生成上面输出的测试数据:
复制代码 代码如下:

quarter; quarter; quarter; chips;
dollar; dollar; toothpaste;
quarter; dime; abort_transaction;
quarter; dime; soda;
quarter; dime; nickel; soda;
abort_transaction;
stop;
///:~

多重拆封
  当处理多个类型之间的交互的时候代码很有可能变得杂乱,例如number.plush(number),number.mutiply(number)等,number仅仅是个家族的基类,那么当你调用a.plus(b)的时候,你既不知道a的类型也不知道b的类型,那么如何保证他们之间的交互正确呢?java只能执行单重拆封,也就是如果在执行多个未知类型的一个或者多个操作的时候,java只能对其中的一个类型执行动态绑定机制,这样不能解决我们上面谈到的问题,因此不得不手动书写动态绑定的代码。
  解决方案是使用多重绑定。多态只能在调用方法的时候发生,因此如果你需要多重拆封,必须调用多个方法。通过多重拆封,你必须有一个虚方法来调用每个类型的方法来进行拆封。下面的例子是一个剪刀石头布的实例:
复制代码 代码如下:

//: enumerated/outcome.java
package enumerated;
public enum outcome { win, lose, draw } ///:~
//: enumerated/roshambo1.java
// demonstration of multiple dispatching.
package enumerated;
import java.util.*;
import static enumerated.outcome.*;
interface item {
  outcome compete(item it);
  outcome eval(paper p);
  outcome eval(scissors s);
  outcome eval(rock r);
}
class paper implements item {
  public outcome compete(item it) { return it.eval(this); }
  public outcome eval(paper p) { return draw; }
  public outcome eval(scissors s) { return win; }
  public outcome eval(rock r) { return lose; }
  public string tostring() { return "paper"; }
}
class scissors implements item {
  public outcome compete(item it) { return it.eval(this); }
  public outcome eval(paper p) { return lose; }
  public outcome eval(scissors s) { return draw; }
  public outcome eval(rock r) { return win; }
  public string tostring() { return "scissors"; }
}
class rock implements item {
  public outcome compete(item it) { return it.eval(this); }
  public outcome eval(paper p) { return win; }
  public outcome eval(scissors s) { return lose; }
  public outcome eval(rock r) { return draw; }
  public string tostring() { return "rock"; }
}
public class roshambo1 {
  static final int size = 20;
  private static random rand = new random(47);
  public static item newitem() {
    switch(rand.nextint(3)) {
      default:
      case 0: return new scissors();
      case 1: return new paper();
      case 2: return new rock();
    }
  }
  public static void match(item a, item b) {
    system.out.println(a + " vs. " + b + ": " + a.compete(b));
  }
  public static void main(string[] args) {
    for(int i = 0; i < size; i++)
      match(newitem(), newitem());
  }
} /* output:
rock vs. rock: draw
paper vs. rock: win
paper vs. rock: win
paper vs. rock: win
scissors vs. paper: win
scissors vs. scissors: draw
scissors vs. paper: win
rock vs. paper: lose
paper vs. paper: draw
rock vs. paper: lose
paper vs. scissors: lose
paper vs. scissors: lose
rock vs. scissors: win
rock vs. paper: lose
paper vs. rock: win
scissors vs. paper: win
paper vs. scissors: lose
paper vs. scissors: lose
paper vs. scissors: lose
paper vs. scissors: lose
*///:~

我们使用了很多手段来实现多重拆封,但是获得的是良好的代码结构。使用枚举的解决方案来实现上面的代码的时候最大的问题就是枚举实例不是类型,因此不能使用枚举实例来作为参数类型。但是我们还是可以有其他的方法绕狗这个障碍,一种方法就是使用构造器来初始化每个枚举类型,然后将输出组织称一个查找表:
复制代码 代码如下:

//: enumerated/roshambo2.java
// switching one enum on another.
package enumerated;
import static enumerated.outcome.*;
public enum roshambo2 implements competitor<roshambo2> {
  paper(draw, lose, win),scissors(win, draw, lose),rock(lose, win, draw);
  private outcome vpaper, vscissors, vrock;
  roshambo2(outcome paper,outcome scissors,outcome rock) {
    this.vpaper = paper;
    this.vscissors = scissors;
    this.vrock = rock;
  }
  public outcome compete(roshambo2 it) {
    switch(it) {
      default:
      case paper: return vpaper;
      case scissors: return vscissors;
      case rock: return vrock;
    }
  }
  public static void main(string[] args) {
    roshambo.play(roshambo2.class, 20);
  }
} /* output:
rock vs. rock: draw
scissors vs. rock: lose
scissors vs. rock: lose
enumerated types 753
scissors vs. rock: lose
paper vs. scissors: lose
paper vs. paper: draw
paper vs. scissors: lose
rock vs. scissors: win
scissors vs. scissors: draw
rock vs. scissors: win
scissors vs. paper: win
scissors vs. paper: win
rock vs. paper: lose
rock vs. scissors: win
scissors vs. rock: lose
paper vs. scissors: lose
scissors vs. paper: win
scissors vs. paper: win
scissors vs. paper: win
scissors vs. paper: win
*///:~

复制代码 代码如下:

//: enumerated/competitor.java
// switching one enum on another.
package enumerated;
public interface competitor<t extends competitor<t>> {
  outcome compete(t competitor);
} ///:~

复制代码 代码如下:

//: enumerated/roshambo.java
// common tools for roshambo examples.
package enumerated;
import net.mindview.util.*;
public class roshambo {
  public static <t extends competitor<t>> void match(t a, t b) {
    system.out.println(a + " vs. " + b + ": " + a.compete(b));
  }
  public static <t extends enum<t> & competitor<t>> void play(class<t> rsbclass, int size) {
    for(int i = 0; i < size; i++)
      match(enums.random(rsbclass),enums.random(rsbclass));
  }
} ///:~

因为制定静态方法可以为每个枚举类型提供不同的方法,看起来是一个实现多重拆封的好解决办法,但是还是面临着枚举实例不是类型的问题,于是我们能做的就是添加一个switch语句:
复制代码 代码如下:

//: enumerated/roshambo3.java
// using constant-specific methods.
package enumerated;
import static enumerated.outcome.*;
public enum roshambo3 implements competitor<roshambo3> {
  paper {
    public outcome compete(roshambo3 it) {
      switch(it) {
        default: // to placate the compiler
        case paper: return draw;
        case scissors: return lose;
        case rock: return win;
      }
    }
  },
  scissors {
    public outcome compete(roshambo3 it) {
      switch(it) {
        default:
        case paper: return win;
        case scissors: return draw;
        case rock: return lose;
      }
    }
  },
  rock {
    public outcome compete(roshambo3 it) {
      switch(it) {
        default:
        case paper: return lose;
        case scissors: return win;
        case rock: return draw;
      }
    }
  };
  public abstract outcome compete(roshambo3 it);
  public static void main(string[] args) {
    roshambo.play(roshambo3.class, 20);
  }
} /* same output as roshambo2.java *///:~

下面的代码是一种更加简洁的实现方法:
复制代码 代码如下:

//: enumerated/roshambo4.java
package enumerated;
public enum roshambo4 implements competitor<roshambo4> {
  rock {
    public outcome compete(roshambo4 opponent) {
      return compete(scissors, opponent);
    }
  },
  scissors {
    public outcome compete(roshambo4 opponent) {
      return compete(paper, opponent);
    }
  },
  paper {
    public outcome compete(roshambo4 opponent) {
      return compete(rock, opponent);
    }
  };
  outcome compete(roshambo4 loser, roshambo4 opponent) {
    return ((opponent == this) ? outcome.draw: ((opponent == loser) ? outcome.win: outcome.lose));
  }
  public static void main(string[] args) {
    roshambo.play(roshambo4.class, 20);
  }
} /* same output as roshambo2.java *///:~

enummap类似乎是一个可以真正实现多重拆封的好办发:
复制代码 代码如下:

//: enumerated/roshambo5.java
// multiple dispatching using an enummap of enummaps.
package enumerated;
import java.util.*;
import static enumerated.outcome.*;
enum roshambo5 implements competitor<roshambo5> {
  paper, scissors, rock;
  static enummap<roshambo5,enummap<roshambo5,outcome>> table = new enummap<roshambo5,enummap<roshambo5,outcome>>(roshambo5.class);
  static {
    for(roshambo5 it : roshambo5.values())
      table.put(it, new enummap<roshambo5,outcome>(roshambo5.class));
    initrow(paper, draw, lose, win);
    initrow(scissors, win, draw, lose);
    initrow(rock, lose, win, draw);
  }
  static void initrow(roshambo5 it, outcome vpaper, outcome vscissors, outcome vrock) {
    enummap<roshambo5,outcome> row = roshambo5.table.get(it);
    row.put(roshambo5.paper, vpaper);
    row.put(roshambo5.scissors, vscissors);
    row.put(roshambo5.rock, vrock);
  }
  public outcome compete(roshambo5 it) {
    return table.get(this).get(it);
  }
  public static void main(string[] args) {
    roshambo.play(roshambo5.class, 20);
  }
} /* same output as roshambo2.java *///:~

我们还可以使用枚举实例具有固定值的特点来使用数据进行最简单的实现方法,这里使用一个二维数组进行映射来实现:
复制代码 代码如下:

//: enumerated/roshambo6.java
// enums using "tables" instead of multiple dispatch.
package enumerated;
import static enumerated.outcome.*;
enum roshambo6 implements competitor<roshambo6> {
  paper, scissors, rock;
  private static outcome[][] table = {
    { draw, lose, win }, // paper
    { win, draw, lose }, // scissors
    { lose, win, draw }, // rock
  };
  public outcome compete(roshambo6 other) {
    return table[this.ordinal()][other.ordinal()];
  }
  public static void main(string[] args) {
    roshambo.play(roshambo6.class, 20);
  }
} ///:~