Enumerated Types

Basic enum features

  • When you create an enum, an associated class is produced for you by the compiler. This class is automatically inherited from java.lang.Enum.
  • The ordinal( ) method produces an int indicating the declaration order of each enum instance, starting from zero.

Using static imports with enums

  • Is it better to be explicit and qualify all enum instances? It probably depends on the complexity of your code.

Adding methods to an enum

  • Except for the fact that you can’t inherit from it, an enum can be treated much like a regular class.
  • You may want to produce different descriptions for an enumeration than the default toString( ).
  • If you are going to define methods you must end the sequence of enum instances with a semicolon.
  • Java forces you to define the instances as the first thing in the enum.
  • The constructor can only be used to create the enum instances that you declare inside the enum definition.
  • The compiler won’t let you use it to create any new instances once the enum definition is complete.

Overriding enum methods

  • Overriding the toString( ) method for an enum is the same as overriding it for a regular class.

enums in switch statements

  • Ordinarily, a switch only works with an integral value, but since enums have an established integral order and the order of an instance can be produced with the ordinal( ) method, enums can be used in switch statements.
  • Although normally you must qualify an enum instance with its type, you do not have to do this in a case statement.
  • The compiler does not complain that there is no default statement inside the switch.
  • On the other hand, if you are calling return from case statements, the compiler will complain if you don’t have a default.

The mystery of values()

  • If you look at Enum, you’ll see that there is no values( ) method, even though we’ve been using it.
  • values( ) is a static method that is added by the compiler.
  • In the output, you can see that Explore has been made final by the compiler, so you cannot inherit from an enum.
  • Because values( ) is a static method inserted into the enum definition by the compiler, if you upcast an enum type to Enum, the values( ) method will not be available.
  • Even if values( ) is not part of the interface of Enum, you can still get the enum instances via the Class object.

Implements, not inherits

  • All enums extend java.lang.Enum. Since Java does not support multiple inheritance, this means that you cannot create an enum via inheritance.
  • It is possible to create an enum that implements one or more interfaces.

Using interfaces for organization

  • The motivation for inheriting from an enum comes partly from wanting to extend the number of elements in the original enum, and partly from wanting to create subcategories by using subtypes.
  • You can achieve categorization by grouping the elements together inside an interface and creating an enumeration based on that interface.
  • Another, more compact, approach to the problem of categorization is to nest enums within enums.

Using EnumSet instead of flags

  • An enum requires that all its members be unique, so it would seem to have set behavior, but since you can’t add or remove elements it’s not very useful as a set.
  • Internally, it is represented by (if possible) a single long that is treated as a bit-vector, so it’s extremely fast and efficient.
  • EnumSets are built on top of longs, a long is 64 bits, and each enum instance requires one bit to indicate presence or absence. This means you can have an EnumSet for an enum of up to 64 elements without going beyond the use of a single long.

Using EnumMap

  • An EnumMap is a specialized Map that requires that its keys be from a single enum.
  • An EnumMap can be implemented internally as an array.
  • You can only call put( ) for keys that are in your enum, but other than that it’s like using an ordinary Map.
  • The order of elements in the EnumMap is determined by their order of definition in the enum.
  • An EnumMap allows you to change the value objects, whereas constant-specific methods are fixed at compile time.

Constant-specific methods

  • You define one or more abstract methods as part of the enum, then define the methods for each enum instance.
  • You can look up and call methods via their associated enum instance.
  • Each instance is a distinct type.
  • You cannot treat enum instances as class types.
  • Because they are static, enum instances of inner enums do not behave like ordinary inner classes.
  • It is possible to override constant-specific methods, instead of implementing an abstract method.

Chain of Responsibility with enums

  • In the Chain of Responsibility design pattern, you create a number of different ways to solve a problem and chain them together.
  • When a request occurs, it is passed along the chain until one of the solutions can handle the request.
  • Each strategy is tried in turn until one succeeds or they all fail.

State machines with enums

  • Enumerated types can be ideal for creating state machines.
  • Because enums restrict the set of possible cases, they are quite useful for enumerating the different states and inputs.

Multiple dispatching

  • Java only performs single dispatching.
  • If you are performing an operation on more than one object whose type is unknown, Java can invoke the dynamic binding mechanism on only one of those types.
  • If you want double dispatching, there must be two method calls: the first to determine the first unknown type, and the second to determine the second unknown type.
  • Generally, you’ll set up a configuration such that a single method call produces more than one virtual method call and thus services more than one type in the process.

Dispatching with enums

  • You can’t use enum instances as argument types.
  • There are a number of different approaches to implementing multiple dispatching which benefit from enums.

Using constant-specific methods

  • Because constant-specific methods allow you to provide different method implementations for each enum instance, they might seem like a perfect solution for setting up multiple dispatching.

Dispatching with EnumMaps

  • It’s possible to perform a "true" double dispatch using the EnumMap class, which is specifically designed to work very efficiently with enums.

Using a 2-D array

  • A two-dimensional array mapping the competitors onto the outcomes produces the smallest and most straightforward solution.
  • It’s not quite as "safe" as the previous examples because it uses an array.

Thinking in Java——笔记(19)的更多相关文章

  1. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

  2. java笔记00-目录

    --2013年7月26日17:49:59 学习java已久,趁最近有空,写一个总结: java笔记01-反射:

  3. Ext.Net学习笔记19:Ext.Net FormPanel 简单用法

    Ext.Net学习笔记19:Ext.Net FormPanel 简单用法 FormPanel是一个常用的控件,Ext.Net中的FormPanel控件同样具有非常丰富的功能,在接下来的笔记中我们将一起 ...

  4. Java笔记(二十五)……其他常用API

    System类 工具类全部都是静态方法 常用方法 获取系统属性信息 static PropertiesgetProperties() static StringgetProperty(String k ...

  5. Java基础知识强化之网络编程笔记19:Android网络通信之 HttpClient和传统Post、Get方式的区别

    1. HttpClient是什么 ?     HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 ...

  6. Java基础知识强化之集合框架笔记19:List集合迭代器使用之 并发修改异常的产生原因 以及 解决方案

    1. 我有一个集合,如下,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现. ConcurrentModi ...

  7. Java基础知识强化之IO流笔记19:FileOutputStream的三个write方法

    1. FileOutputStream的三个write方法:  void write(byte[] buffer)           Writes the entire contents of th ...

  8. java新手笔记19 抽象类

    1.Shap package com.yfs.javase; public class Shape /*extends Object */{ //默认继承object object方法全部继承 //计 ...

  9. java笔记--理解java类加载器以及ClassLoader类

    类加载器概述: java类的加载是由虚拟机来完成的,虚拟机把描述类的Class文件加载到内存,并对数据进行校验,解析和初始化,最终形成能被java虚拟机直接使用的java类型,这就是虚拟机的类加载机制 ...


  1. 如何做优化,UITabelView才能更加顺滑 (转载)

    这篇文章是前两周@叶孤城叶大在微信群里面的分享,一直到这两天才翻出来研究.很多实用的东西,不过由于水平有限,有些地方没能翻译好,还请大家指正. 我已经在iOS这个最好的移动平台上有几年的开发经验了.在 ...

  2. iOS - AliPay 支付宝支付

    1.支付宝支付申请 支付宝支付官方签约集成指引 支付宝APP支付官方集成指引 蚂蚁金服开放平台 1.1 支付宝 APP 支付申请步骤 APP 支付:APP 支付是商户通过在移动端应用 APP 中集成开 ...

  3. 调用C++动态链接库出现错误

    解决方式:将托管 System.String 中的内容复制到非托管内存(Marshal.StringToHGlobalAnsi) class HttpsSend { [DllImport(" ...

  4. SQL计算时间差,要精确到小时分钟秒

    declare @starttime as datetime declare @endtime as datetime set @starttime = '2009-11-24 15:10:00' s ...

  5. (转载)iOS 极光推送SDK 集成指南

    iOS SDK 集成指南 使用提示 本文匹配的 SDK版本:r1.2.5 以后. 查看最近更新了解最新的SDK更新情况. 产品功能说明 极光推送(JPush)是一个端到端的推送服务,使得服务器端消息能 ...

  6. ArcGIS10.1 api for Flex开发用于ArcGIS 9.3时QueryTask 'Error #2032'错误的解决方案

    因客户GIS软件需求,将应用降级到低版本ArcGIS9.3,不仅数据有些样式.配色.字符有些问题,API也要相应“降级”,解决如下: 利用9.3+flex做QueryTask时候出现了[RPC Fau ...

  7. 微软自带的Serialization和Newtonsoft简单测试

    刚刚对这两个进行了一下小小的测试 发现 当转换的内容少的时候  微软自带的比Newtonsoft速度要快一些,内容多的时候反之,当内容多到一定量的时候微软自带的就不能转换了,需要修改一下MaxJson ...

  8. spring文件下载记录

    /** * 下载方法 * @param request * @param response * @param storeName 文件在存在位置的名字(需要带着后缀) * @param content ...

  9. 再谈this

    不管学习什么知识,习惯于把自己所学习的知识列成一个list,会有助于我们理清思路,是一个很好的学习方法.强烈推荐. 以下篇幅有点长,希望读者耐心阅读. 以下内容会分为如下部分: 1.涵义 1.1:th ...

  10. 在Eclipse中配置Tomcat 创建和运行Servlet/JSP

    在Eclipse中配置Tomcat 创建和运行Servlet/JSP 步骤一:在Eclipse中配置Tomcat(注意下载Eclipse IDE for Java EE Developers) (1) ...