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学习笔记之使用百度地图实现路线规划+公交信息检索

    PS:装了个deepin,感觉真的很高大上. 学习内容: 1.公交信息检索 2.路线规划   关于百度地图的开发也就这么多了.重要的部分也就那么些.原本打算搞到poi搜索就算了,不过看到了这两个方面还 ...

  2. Android开发总结

    出来工作半年多了,没啥好交代的,就说说自己半年来的Android开发经历. 1.IDE      这半年来,从Eclipse到Android Studio,经历了两个IDE,在这里做一下简单的评价. ...

  3. 阅读Nosql代码有感

    这一年总得来说,读书的时间不多.一是因为时间啥关系,这一年一直在跟着项目走,或者被项目牵着走,几乎所有的时间和精力全部被拴在几个项目上:不过所幸今年创业失败,又回去上班了,时间相对空余了一些. 双十一 ...

  4. Qt Style Sheet实践(四):行文本编辑框QLineEdit及自动补全

    导读 行文本输入框在用于界面的文本输入,在WEB登录表单中应用广泛.一般行文本编辑框可定制性较高,既可以当作密码输入框,又可以作为文本过滤器.QLineEdit本身使用方法也很简单,无需过多的设置就能 ...

  5. 字符串hash + 二分答案 - 求最长公共子串 --- poj 2774

    Long Long Message Problem's Link:http://poj.org/problem?id=2774 Mean: 求两个字符串的最长公共子串的长度. analyse: 前面在 ...

  6. 正则表达式相关:C# 抓取网页类(获取网页中所有信息)

    类的代码: using System; using System.Data; using System.Configuration; using System.Net; using System.IO ...

  7. jquery实现网页选项卡

    这个功能在现在的网站中使用较为普遍,就是以选项卡的形式来对一些内容做了分类.,比如下面的天猫商城. 下面的源码是仿照天猫写的一个选项卡,实现起来的效果如下. 主要是利用我们在点击相应板块是触发它的单击 ...

  8. 回文串---Palindrome

    POJ   3974 Description Andy the smart computer science student was attending an algorithms class whe ...

  9. linux系统如何将系统中的文件名改为英文?

    由于我们经常在命令行模式下进入文件,那么中英文的切换常常会影响我们输入的效率. 那么如何将原来的中文修改成英文的字幕呢? 如下图所示: -------------------------------- ...

  10. ahjesus 安装mongodb企业版for ubuntu

    导入共匙 sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 创建源列表 echo 'deb http ...