Java EnumMap工作原理及实现(二)
2016-05-17 13:24
441 查看
1.概述
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation
is extremely compact and efficient.
EnumMap是是一种键为枚举类型的特殊的Map实现。所有的Key也必须是一种枚举类型,EnumMap是使用数组来实现的。
输出结果为:
其具体实现的结构如下图所示:
通过hasNext跳过空的数组,也就是说,保证了遍历顺序与Enum中key的先后顺序一致。
本文转载自:点击打开链接
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation
is extremely compact and efficient.
EnumMap是是一种键为枚举类型的特殊的Map实现。所有的Key也必须是一种枚举类型,EnumMap是使用数组来实现的。
1 2 3 4 5 6 7 8 | EnumMap<Course, String> map = new EnumMap<Course, String>(Course.class); map.put(Course.ONE, "语文"); map.put(Course.ONE, "政治"); map.put(Course.TWO, "数学"); map.put(Course.THREE, "英语"); for(Entry<Course, String> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } |
1 2 3 | ONE: 政治 TWO: 数学 THREE: 英语 |
2. put和get方法
put方法通过key的ordinal将值存储到对应的地方,get方法则根据key的ordinal获取对应的值。1 2 3 4 5 6 7 89 | public V put(K key, V value) { // 类型检查 typeCheck(key); // 获取key的序号 int index = key.ordinal(); Object oldValue = vals[index]; // 赋值 vals[index] = maskNull(value); // 若之前的值为空,则size++ if (oldValue == null) size++; return unmaskNull(oldValue); } public V get(Object key) { return (isValidKey(key) ? unmaskNull(vals[((Enum<?>)key).ordinal()]) : null); } |
3. 遍历
EnumMapIterator的迭代这样实现的:1 2 3 4 5 6 7 89 | public boolean hasNext() { while (index < vals.length && vals[index] == null) index++; return index != vals.length; } public Map.Entry<K,V> next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedEntry = new Entry(index++); return lastReturnedEntry; } |
本文转载自:点击打开链接
参考资料
What is EnumMap in Java相关文章推荐
- Java序列化与反序列化
- 深入JDK源码_Index --> 深入JDK源码之ThreadLocal类 --> 陶邦仁 又发现一牛人
- Java EnumMap工作原理及实现(一)
- Java StackTraceElement的使用与理解
- java中父类加载机制
- java反射——运用反射生成jdk动态代理
- 《JAVA继承与多态》利用继承实现MyStack,MyStack是用组合实现的。扩展ArrayLis
- eclipse运行maven install报错
- IT十八掌掌第九天课程总结
- struts2处理.do后缀de请求
- javaweb学习总结(十六)——JSP指令
- Java总结篇系列:Java多线程
- Java中 char和int之间的转换
- java编码规范及优化总结
- JAVA设计模式(01):创建型-工厂模式【简单工厂模式】(Simple Factory)
- Spring MVC入门
- java 中 null 与""的区别
- sun.misc.BASE64Encoder找不到jar包的解决方法(eclipse中红叉)
- 5.17 JAVA
- java之斐波拉契问题(生兔子)