Enumerated type is a type whose legal values consist of a fixed set of constants, such as the seasons of the year.

// 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;

The basic idea behind Java's enum types is simple: they are classes that export one instance for each enumeration constant via a public static final field.

To associate data with enum constants, declare instance fields and write a constructor that takes the data and stores it in the fields.

Note

  1. unless you have a compelling reason to expose an enum method to its clients, declare it private or, if need be, package-private (Item 13).
  2. If an enum is generally useful, it should be a top-level class; if its use is tied to

    a specific top-level class, it should be a member class of that top-level class (Item22)

  3. Compiler will reminds you that abstract methods in an enum type must be overridden with concrete methods in all of its constants.

    /**

    * Demo for enum type use abstract methods for Compile time checking on added enum type.

    */

    package com.effectivejava.EnumAnnotations;

    import java.util.HashMap;

    import java.util.Map;

    /**

    * @author Kaibo

    *

    */

    public enum Operation {

    PLUS("+") {

    public double apply(double x, double y) {

    return x + y;

    }

    },

    MINUS("-") {

    public double apply(double x, double y) {

    return x - y;

    }

    },

    TIMES("*") {

    public double apply(double x, double y) {

    return x * y;

    }

    },

    DIVIDE("/") {

    public double apply(double x, double y) {

    return x / y;

    }

    };

    private final String symbol;

    Operation(String symbol) {

    this.symbol = symbol;

    }

    @Override

    public String toString() {

    return symbol;

    }

    public abstract double apply(double x, double y);

    }

    Note

    Enum types have an automatically generated valueOf(String)method that translates a constant's name into the constant itself. If you override the toString method in an enum type, consider writing a fromString method to translate the custom string representation back to the corresponding enum.

    // Implementing a fromString method on an enum type

    private static final Map<String, Operation> stringToEnum = new HashMap<String, Operation>();

    static { // Initialize map from constant name to enum constant

    for (Operation op : values())

    stringToEnum.put(op.toString(), op);

    }

// Returns Operation for string, or null if string is invalid

public static Operation fromString(String symbol) {

return stringToEnum.get(symbol);

}

4. Use nested enum for the strategy enum pattern. Using constant-specific methods.

/**

* Demo for the "Using Nested enum for enum strategy pattern."

*/

package com.effectivejava.EnumAnnotations;

/**

* @author Kaibo

*

*/

// The strategy enum pattern

enum PayrollDay {

MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(

PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(

PayType.WEEKEND), SUNDAY(PayType.WEEKEND);

private final PayType payType;

PayrollDay(PayType payType) {

this.payType = payType;

}

double pay(double hoursWorked, double payRate) {

return payType.pay(hoursWorked, payRate);

}

// The strategy enum type

private enum PayType {

// constant-specific methods

WEEKDAY {

double overtimePay(double hours, double payRate) {

return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT)

* payRate / 2;

}

},

WEEKEND {

double overtimePay(double hours, double payRate) {

return hours * payRate / 2;

}

};

private static final int HOURS_PER_SHIFT = 8;

abstract double overtimePay(double hrs, double payRate);

double pay(double hoursWorked, double payRate) {

double basePay = hoursWorked * payRate;

return basePay + overtimePay(hoursWorked, payRate);

}

}

}

5. Switches on enums are good for augmenting external enum types with constant-specific behavior.

// Switch on an enum to simulate a missing method

public static Operation inverse(Operation op) {

switch(op) {

case PLUS: return Operation.MINUS;

case MINUS: return Operation.PLUS;

case TIMES: return Operation.DIVIDE;

case DIVIDE: return Operation.TIMES;

default: throw new AssertionError("Unknown op: " + op);

}

}

Summary

Enums are far more readable, safer, and more powerful than int constants. Enums can benefit from associating data with each constant sand providing methods whose behavior is affected by this data. When enums benefit from assocating multiple behaviors with a single method perfer constant-specific methods to enums that switch on their own values. Consider the strategy enum pattern if multiple enum constants share common behaviors.

Effective Java 30 Use Enums instead of int constants的更多相关文章

  1. effective java——30使用enum

    1, 枚举太阳系八大行星 package com.enum30.www; public enum Planet {//枚举太阳系八大行星 MERCURY(3.302e+23,2.439e6), VEN ...

  2. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  3. 《Effective Java》读书笔记 - 6.枚举和注解

    Chapter 6 Enums and Annotations Item 30: Use enums instead of int constants Enum类型无非也是个普通的class,所以你可 ...

  4. Effective Java 第三版——30. 优先使用泛型方法

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  5. Effective Java之避免创建不必要的对象

    Effective Java中有很多值得注意的技巧,今天我刚开始看这本书,看到这一章的时候,我发现自己以前并没有理解什么是不必要的对象,所以拿出来跟大家探讨一下,避免以后犯不必要的错误! 首先书中对不 ...

  6. [Effective Java]第八章 通用程序设计

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  7. 对于所有对象都通用方法的解读(Effective Java 第二章)

    这篇博文主要介绍覆盖Object中的方法要注意的事项以及Comparable.compareTo()方法. 一.谨慎覆盖equals()方法 其实平时很少要用到覆盖equals方法的情况,没有什么特殊 ...

  8. Effective Java通俗理解(持续更新)

    这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...

  9. Effective Java通俗理解(下)

    Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...

随机推荐

  1. 禁用mac Command w

    事情是这样的:历经各种调查,终于定位到了一个bug,正在我准确Command + 数字 切换下iterm2的窗口时,让我懵逼的事情发生了,我们终端不见了,对不见了.心里万马奔腾啊.什么鬼?原来自己误按 ...

  2. sprint2 项目部署+展示

    项目展示网址: http://160q49b998.51mypc.cn/ (注:所有用户密码都为123456,校内断网时访问不了)

  3. Qt Style Sheet实践(二):组合框QComboBox的定制

    导读 组合框是一个重要且应用广泛的组件,一般由两个子组件组成:文本下拉单部分和按钮部分.在许多既需要用户选择.又需要用户手动输入的应用场景下,组合框能够很好的满足我们的需求.如我们经常使用的聊天软件Q ...

  4. JavaScript 的数据类型 相关知识点

    (1)基本数据类型介绍 JavaScript的数据类型分为两类:原始类型(primitive type)和对象类型(object type) 或者说是:可以拥有方法的类型和不能拥有方法的类型 或者说是 ...

  5. 支付宝支付集成,上传RSA公钥一直显示格式错误

    碰到同样的问题,支付宝的问题,已有解决方案:https://openhome.alipay.com/platform/keyManage.htm?keyType=partner

  6. jQuery点缩略图显示大图片

    2015年繁忙的一月份,无更多时间去学习ASP.NET MVC程序,二月份又是中国的新年,长达半个月的假期,望回到老家中,在无电脑无网络的日子里,能有更多时间陪伴年迈的父母亲. 今天学习jQuery的 ...

  7. 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract

    [源码下载] 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps ...

  8. EffectiveJava——复合优先于继承

    继承时实现代码重用的重要手段,但它并非永远是完成这项工作的最佳工具,不恰当的使用会导致程序变得很脆弱,当然,在同一个程序员的控制下,使用继承会变的非常安全.想到了很有名的一句话,你永远不知道你的用户是 ...

  9. PHP学习笔记:伪静态规则的书写

    这里以阿帕奇为服务器软件,直接上案例: 1.把index.html重定向到index.php RewriteEngine On Options -Indexes ReWriteRule ^index. ...

  10. mysqli连接数据库常见函数

    mysqli_free_result() 返回最后一次查询中使用的自动生成 id,如果是多表插入,返回的是第一个被插入的id. mysqli_query($con,"INSERT INTO ...