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. Java笔记19:Java匿名内部类

    匿名内部类也就是没有名字的内部类.正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写.但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口 例1:不使用匿名内部类来实现抽象方 ...

  2. JAVA自学笔记19

    JAVA自学笔记19 1.集合总结 Collection(单列集合) List(有序可重复) ArrayList:底层数据结构是数组 ,查询快,增删慢.线程不安全,效率高 Vector:底层数据结构是 ...

  3. java笔记整理

    Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...

  4. springmvc学习笔记(19)-RESTful支持

    springmvc学习笔记(19)-RESTful支持 标签: springmvc springmvc学习笔记19-RESTful支持 概念 REST的样例 controller REST方法的前端控 ...

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

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

  6. java笔记00-目录

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

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

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

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

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

  9. SQL反模式学习笔记19 使用*号,隐式的列

    目标:减少输入 反模式:捷径会让你迷失方向 使用通配符和未命名的列能够达到减少输入的目的,但是这个习惯会带来一些危害. 1.破坏代码重构:增加一列后,使用隐式的Insert插入语句报错: 2.查询中使 ...

随机推荐

  1. SQL Server对比两字段的相似度(函数算法)

    相似度函数 概述    比较两个字段的相似度    最近有人问到关于两个字段求相似度的函数,所以就写了一篇关于相似度的函数,分别是“简单的模糊匹配”,“顺序匹配”,“一对一位置匹配”.在平时的这种函数 ...

  2. Android学习——第一个NDK程序

    在前面的学习中,我们已经讲解了关于NDK编程的环境搭建流程,简单的使用我们也通过官网本身自带的例子进行说明了.可是相信大家一定还存在这么的一个疑惑:“如果我要自己利用NDK编写一个Android应用, ...

  3. C语言 · 十六进制转十进制

    问题描述 从键盘输入一个不超过8位的正的十六进制数字符串,将它转换为正的十进制数后输出. 注:十六进制数中的10~15分别用大写的英文字母A.B.C.D.E.F表示. 样例输入 FFFF 样例输出 6 ...

  4. 在JS中获取文件点之后的后缀字符

    var upFileName = $("#fileToUpload").val();var index1=upFileName.lastIndexOf(".") ...

  5. Apache Spark源码剖析

    Apache Spark源码剖析(全面系统介绍Spark源码,提供分析源码的实用技巧和合理的阅读顺序,充分了解Spark的设计思想和运行机理) 许鹏 著   ISBN 978-7-121-25420- ...

  6. Elasticsearch5.0 安装问题集锦

    使用Elasticsearch5.0 必须安装jdk1.8 [elsearch@vm-mysteel-dc-search01 bin]$ java -version java version &quo ...

  7. 使用未付费的账号真机调试 iOS 程序,过几天后程序一打开就会闪退

    使用未付费的苹果开发者账号真机调试 iOS 程序,过几天后程序一打开就会闪退.   解决办法: 删除 Provisioning Profile,重新配置一次. 终极解决办法:花钱购买苹果开发者账号. ...

  8. 实战MEF(3):只导出类的成员

    通过前面两篇文章的介绍,相信各位会明白MEF中有不少实用价值.上一文中我们也讨论了导入与导出,对于导出导入,今天我们再深入一点点,嗯,只是深入一点点而已,不会很难的,请大家务必放心,如果大家觉得看文章 ...

  9. OpenCASCADE Root-Finding Algorithm

    OpenCASCADE Root-Finding Algorithm eryar@163.com Abstract. A root-finding algorithm is a numerical m ...

  10. 应用程序框架实战十七:DDD分层架构之值对象(层超类型篇)

    上一篇介绍了值对象的基本概念,得到了一些朋友的支持,另外也有一些朋友提出了不同意见.这其实是很自然的事情,设计本来就充满了各种可能性,没有绝对正确的做法,只有更好的实践.但是设计与实践的好与坏,对于不 ...