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. Android学习笔记之DocumentBuilder的使用....

    PS:当你的才华还撑不起你的野心时,那你需要静下心来学习..... 学习内容: 1.从服务器上获取XML文档... 2.解析XML文档中的内容...   XML文件想必大家都非常的熟悉,可扩展的标记语 ...

  2. 自增长的聚集键值不会扩展(scale)

    如何选择聚集键值的最佳实践是什么?一个好的聚集键值应该有下列属性: 范围小的(Narrow) 静态的(Static) 自增长的(Ever Increasing) 我们来具体看下所有这3个属性,还有在S ...

  3. 2013/11/22工作随笔-缓存是放在Model层还是放在Controller层

    web网站的典型代码框架就是MVC架构,Model层负责数据获取,Controller层负责逻辑控制,View层则负责展示. 一般数据获取是去mysql中获取数据 但是这里有个问题,我们不会每次请求都 ...

  4. Web前端面试题集锦

    前端开发面试知识点大纲: 注意 转载须保留原文链接(http://www.cnblogs.com/wzhiq896/p/5927180.html )作者:wangwen896 HTML&CSS ...

  5. ASP.NET运行时详解 生命周期入口分析

    说起ASP.NET的生命周期,网上有很多的介绍.之前也看了些这方面的博客,但我感觉很多程序猿像我一样,看的时候似乎明白,一段时间过后又忘了.所以,最近Heavi花了一段时间研究ASP.NET的源代码, ...

  6. Symantec Backup Exec恢复数据库

    Insus.NET是使用Symantec Backup Exec来备份数据以及一些服务器文件.下面步骤是怎样恢复一个数据库.当我们数据库有问题,或是想恢复某一天的数据,得需要操作数据恢复Restore ...

  7. Oracle客户端+PLSQLDeveloper实现远程登录Oracle数据库

    Oracle数据库功能强大.性能卓越,在造就这些优点的同时,也导致Oracle占内存比较多.针对这个问题,我们如何做到取其精华去其糟粕呢? 解决方案:我们可以在局域网内的服务器上安装庞大的Oracle ...

  8. 【Bootstrap基础学习】02 Bootstrap的布局组件应用示例

    字体图标的应用示例 <button type="button" class="btn btn-default"> <span class=&q ...

  9. Dynamics AX 中重点数据源方法

     数据源方法 描述   Active  当用户刚选中一行数据时执行该方法.若选中的是主表的数据,也用该方法来触发加载从表符合条件的数据.主要覆盖该方法来根据条件设置记录及其字段是否可见或是否可被编辑. ...

  10. Access数据库的常用数据类型和alter的用法

    一.Access比较常用的数据类型:文本.备注.数字.日期/时间.货币 意思          Sql                    Access 1)文本      nvarchar(30) ...