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年出版,到现在已经将 ...
随机推荐
- 仿照微信的效果,实现了一个支持多选、选原图和视频的图片选择器,适配了iOS6-9系统,3行代码即可集成.
提示:如果你发现了Bug,请尝试更新到最新版.目前最新版是1.6.4,此前的版本或多或少存在一些bug的~如果你已经是最新版了,请留一条评论,我看到了会尽快处理和修复哈~ 关于升级iOS10和Xcdo ...
- GitLab安装说明
GitLab,是一个使用 Ruby on Rails 开发的开源应用程序,与Github类似,能够浏览源代码,管理缺陷和注释,非常适合在团队内部使用. gitlab是基于Ruby on Rails的, ...
- 【团队冲刺总结】一个编码人员的反(tu)思(cao)
消失了半个多月了啊,算算时间,好像确实有近个把月没有好好的写博客来了.我一直很想写博客的,之前有老师问过写博客的动力是什么.我想了想,我觉得可能是我比较喜欢看书吧,不管是专业书还是小说(好吧,我承认, ...
- struts2基础——最简单的一个例子
学习版本:struts-2.3.15.3 一.导入jar包,可以参考 官方项目 blank. 二.添加配置文件:web.xml struts.xml web.xml: <filter> & ...
- 12 19 spring3 项目总结
项目截图: 林集团 https://home.cnblogs.com/u/linjituan/ 团队guihub: https:///github.com/MoiGi 李鹏飞 https://www. ...
- java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)
使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...
- 怎样计算一个整数的位数&并把每一位上的数字保存下来
用循环来解决~~ M每次除以10, 再用一个变量count来计数,每循环一次 加1,直到这个数除去10后的数小于10 ,count再加1就可以了 实例:整数M=4325, 第一次:4325/10=43 ...
- SQL compute by 的使用
SQL compute by 的使用 摘自:http://www.cnblogs.com/Gavinzhao/archive/2010/07/12/1776107.html GROUP BY子句有个缺 ...
- Microsoft.DirectX.DirectSound.dll和Microsoft.DirectX.dll引用,导致项目无法调试问题
最近在做录音功能,用到了Microsoft.DirectX.DirectSound.dll和Microsoft.DirectX.dll两个dll,但是引入后,无法调试项目 具体解决方法: 修改app. ...
- 重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式
[源码下载] 重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 绑定 通过 M ...