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. [Altera] Device Part Number Format

    大体可分为五个部分,不排除有特例. 第一部分说明器件归属的器件系列, 第二部分说明器件的封装类型, 第三部分说明器件的引脚数目, 第四部分说明器件的工作温度范围, 第五部分说明器件的速度等级. 实践中 ...

  2. IT人的自我导向型学习:学习的1个理念和2个心态

    本文更新版本已挪至  http://www.zhoujingen.cn/blog/2484.html ----------------------------- 写这一个系列之前,我定位是与高效学习有 ...

  3. ASP.NET MVC 快速开发框架之 SqlSugar+SyntacticSugar+JQWidgetsSugar+jqwidgets

    jqwidgets.js: 是一个功能完整的框架,它具有专业的可触摸的jQuery插件.主题.输入验证.拖放插件.数据适配器,内置WAI-ARIA(无障碍网页应用)可访问性.国际化和MVVM模式支持. ...

  4. 学期总结ngu

    不知不觉一年就过去了,真可谓光阴似箭,日月如梭,在这一年里,我成长了许多,懂得了如何跟队友合作,提高了我的交际能力,懂得了许多课本知识,增进了我的编写能力.最重要的是学会了总结经验,这无疑是我这一年里 ...

  5. HTML--Table布局

    <DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" Content= ...

  6. CCFlow SDK模式开发

    需求: 1.业务数据要保存在我们自己的数据库里    2.CCFlow有保存草稿的功能,但是领导要求每个业务都要有草稿箱,流程从草稿箱发起,每个业务单独查询,而不要在CCFlow的统一界面查询,所以每 ...

  7. JS 获取 本周、本月、本季度、本年、上月、上周、上季度、去年

    工具类定义: /** * 日期范围工具类 */ var dateRangeUtil = (function () { /*** * 获得当前时间 */ this.getCurrentDate = fu ...

  8. 分享一些WinForm数据库连接界面UI

    1.动软代码生成器源码中. 2.DevExpress控件包中有类似的界面 3.代码生成器:http://www.csharpwin.com/csharpspace/11666r2577.shtml 4 ...

  9. csharp: Sound recording

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsof ...

  10. Java集合框架之Collection接口

    Java是一门面向对象的语言,那么我们写程序的时候最经常操作的便是对象了,为此,Java提供了一些专门用来处理对象的类库,这些类库的集合我们称之为集合框架.Java集合工具包位于Java.util包下 ...