Effective Java 33 Use EnumMap instead of ordinal indexing
Wrong practice: Putting sets into an array indexed by the type's ordinal
/**
* Added demo for the "Use EnumMap instead of ordinal indexing".
*/
package com.effectivejava.EnumAnnotations;
/**
* @author Kaibo
*
*/
public class Herb {
public enum Type {
ANNUAL, PERENNIAL, BIENNIAL
}
private final String name;
public final Type type;
public Herb(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return name;
}
}
// Using ordinal() to index an array - DON'T DO THIS!
Herb[] garden = ... ;
Set<Herb>[] herbsByType = // Indexed by Herb.Type.ordinal()
(Set<Herb>[])new Set[Herb.Type.values().length];
for (int i = 0; i < herbsByType.length; i++)
herbsByType[i] = new HashSet<Herb>();
for (Herb h : garden)
herbsByType[h.type.ordinal()].add(h);
// Print the results
for (int i = 0; i < herbsByType.length; i++) {
System.out.printf("%s: %s%n", Herb.Type.values()[i], herbsByType[i]);
}
Disadvantage of above case
- Arrays are not compatible with generics, so it requires an unchecked cast and will not compile cleanly.
- Array does not know what its index represents, it has to be labeled to the output manually.
- You have to be responsible to use the correct int value of an array; ints do not provide the type safety of enums.
Advantages of using EnumMap for multidimensional sets.
- Clarity
- Safety
- Ease of maintenance.
/**
* Added demo for the "Use EnumMap instead of ordinal indexing".
*/
package com.effectivejava.EnumAnnotations.unittest;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import com.effectivejava.EnumAnnotations.Herb;
/**
* @author Kaibo
*
*/
public class HerbTest {
@Test
public void test() {
// Using ordinal() to index an array - DON'T DO THIS!
Herb[] garden = {new Herb("Flower1",Herb.Type.ANNUAL),
new Herb("Flower2",Herb.Type.BIENNIAL),
new Herb("Flower3",Herb.Type.BIENNIAL)} ;
// Using an EnumMap to associate data with an enum
Map<Herb.Type, Set<Herb>> herbsByType = new EnumMap<Herb.Type, Set<Herb>>(
Herb.Type.class);
for (Herb.Type t : Herb.Type.values())
herbsByType.put(t, new HashSet<Herb>());
for (Herb h : garden)
herbsByType.get(h.type).add(h);
System.out.println(herbsByType);
}
}
Summary
It is rarely appropriate to use ordinals to index arrays: use EnumMap instead. If the relationship that you are representing is multidimensional, use EnumMap<..., EnumMap<...>>.
/**
* Added multidimensional Enum types demo for the "Use EnumMap instead of ordinal indexing".
*/
package com.effectivejava.EnumAnnotations;
import java.util.EnumMap;
import java.util.Map;
/**
* @author Kaibo
*
*/
public enum Phase {
SOLID, LIQUID, GAS;
public enum Transition {
MELT(SOLID, LIQUID), FREEZE(LIQUID, SOLID), BOIL(LIQUID, GAS), CONDENSE(
GAS, LIQUID), SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID);
final Phase src;
final Phase dst;
Transition(Phase src, Phase dst) {
this.src = src;
this.dst = dst;
}
// Initialize the phase transition map
private static final Map<Phase, Map<Phase, Transition>> m = new EnumMap<Phase, Map<Phase, Transition>>(
Phase.class);
static {
for (Phase p : Phase.values())
m.put(p, new EnumMap<Phase, Transition>(Phase.class));
for (Transition trans : Transition.values())
m.get(trans.src).put(trans.dst, trans);
}
public static Transition from(Phase src, Phase dst) {
return m.get(src).get(dst);
}
}
}
Effective Java 33 Use EnumMap instead of ordinal indexing的更多相关文章
- 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 ...
- 《Effective Java》读书笔记 - 6.枚举和注解
Chapter 6 Enums and Annotations Item 30: Use enums instead of int constants Enum类型无非也是个普通的class,所以你可 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- Effective Java 第三版——37. 使用EnumMap替代序数索引
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——33. 优先考虑类型安全的异构容器
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java通俗理解(下)
Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...
- 《Effective Java(中文第二版)》【PDF】下载
<Effective Java(中文第二版)>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382186 Java(中文第二版)& ...
- Effective Java 第三版——35. 使用实例属性替代序数
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——38. 使用接口模拟可扩展的枚举
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
随机推荐
- [mysql]增加用户 授权 远程登录
mysql创建用户和授权 1.创建用户: (注意:下面的指令,请在root用户下输入) CREATE USER "用户名" IDENTIFIED BY "密码" ...
- CentOS6.5菜鸟之旅:安装rpmforge软件库
一.rpmforge软件库 rpmforge是包含4000多种CentOS软件的软件库,被CentOS社区认为是安全和稳定的软件库. 二.安装rpmforege 1. 在http:/ ...
- js代码中的闭包
作为一个后台开发人员了解前端非常重要,尤其是深处学校实验室做项目时前端把写好的代码直接给你,然后你在修改的时候.我经常做的就是修改前端的代码的HTML和后台交互的部分以及js的ajax部分,之后修改之 ...
- 关于c++数的进制的经验
默认状态下,数据按十进制输入输出.如果要求按八进制或十六进制输入输出,在cin或cout中必须指明相应的数据形式,oct为八进制,hex为十六进制,dec为十进制. 注意: 1.使用不带.h的头文件& ...
- LeetCode132:Palindrome Partitioning II
题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...
- x3dom 1.6 发布
X3DOM 库的1.6版本发布了,以下是最重要的一些变化: 完整的新的文档频道 - http://doc.x3dom.org x3dom实例频道 - http://examples.x3dom.or ...
- 防止用户误操作退出APP的处理
/** * 软件退出的处理:先跳到第一个页面,再点提示“再点一次退出”,2秒内再点一次退出 * 防止用户误操作 */ private boolean isExist=false; private Ha ...
- 解决Spring MVC @ResponseBody返回html中中文字符串乱码问题
最近有个应用,通过responsebody返回完整的html页面时出现乱码是异常的问题,因为是通过responsebody返回,所以一开始设置了text/plain的字符集,如下: <mvc:a ...
- jquery只能输入数字方法
本方法为验证文本框的输入内容,如果输入的是数字,则提示"√".否则提示“必填,且只能输入数字字符”.在线体验效果:http://keleyi.com/keleyi/phtml/zz ...
- H5前端面试题及答案(1)
前几天去面试了一家公司,整下改公司的面试题. 1.新的 HTML5 文档类型和字符集是? HTML5 文档类型很简单: <!doctype html> HTML5 使用 UTF-8 编码示 ...