Effective-Java-34用enum代替int常量

枚举类型 (enum type) 是指由一组固定的常量组成合法值的类型,例如一年中的季节、太阳系中的星星或者一副牌中的花色。[1]

在 Java 变成语言引入枚举类型之前,通常是用一组 int 常量 来表示枚举类型,其中每一个 int 表示枚举类型的一个成员:[2]

1
2
3
4
5
6
7
8
// The int enum pattern - severely deficient!
public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPPIN = 1;
public static final int APPLE_GRANNY_SMITH = 2;

public static final int ORANGE_NAVEL = 0;
public static final int ORANGE_TEMPLE = 1;
public static final int ORANGE_BLOOD = 2;

这种方法称作 int 枚举模式 (int enum pattern),他存在许多不足。int 枚举模式无类型安全性,也无描述性可言。[3]

例入将 apple 传到需要 orange 的方法中,编译器也不会产生任何警告,还会用 == 操作符对 apple 与 orange 进行比较,甚至更糟:[4]

1
2
// Tasty citrus flavored applesauce!
int i = (APPLE_FUJI - ORANGE_TEMPLE) / APPLE_PIPPIN;

  1. Java Language Specification SE 21, §8.9 Enum Classes, defines an enum declaration as a restricted class that defines a small set of named class instances; Oracle Java SE 21 API, java.lang.Enum, documents it as the common base class for Java enumeration classes. ↩︎

  2. Joshua Bloch, Effective Java, 3rd Edition, Item 34, frames the recommendation to use enums instead of int constants. ↩︎

  3. Effective Java Item 34 identifies the int enum pattern and explains why it lacks the type-safety and expressiveness supplied by Java enum types. ↩︎

  4. The apple/orange example follows Effective Java Item 34: because both constants are merely int values, the Java type system cannot distinguish the two domains at compile time. ↩︎