java集合架构____EnumMap
EnumMap
以下内容基于jdk1.7.0_79源码;
什么是EnumMap
Map接口的实现,其key-value映射中的key是Enum类型;
补充说明
其原理就是一个对象数组,数组的下标索引就是根据Map中的key直接获取,即枚举中的ordinal值;
效率比HashMap高,可以直接获取数组下标索引并访问到元素;
简单示例
比较简单,源代码就不一一添加注释了,简单地说,就是一个对象数组;
这里稍微了解一下怎么使用就好了,下面列出一些方法的调用示例:
package com.pichen.collection; import java.util.EnumMap; import java.util.Map; import java.util.Map.Entry; enum Operate{ ADD, UPDATE, DELETE; } public class Main { public static void main(String[] args) { Map<Operate, String> map = new EnumMap<Operate, String>(Operate.class); //put方法 map.put(Operate.ADD, "add operate"); map.put(Operate.UPDATE, "update operate"); map.put(Operate.DELETE, "delete operate"); //重写了toString方法 System.out.println(map); //size方法 System.out.println(map.size()); System.out.println(map.containsKey(Operate.UPDATE)); System.out.println(map.containsValue("update operate")); System.out.println(map.get(Operate.DELETE)); //remove map.remove(Operate.UPDATE); System.out.println(map); //key集合 for(Operate operate:map.keySet()){ System.out.print(operate + " "); } System.out.println(); //value集合 for(String obj:map.values()){ System.out.print(obj + ","); } System.out.println(); //key-value集合 for(Entry<Operate, String> entry:map.entrySet()){ System.out.print(entry.getKey() + ": " + entry.getValue() + ", "); } } }
输出结果:
{ADD=add operate, UPDATE=update operate, DELETE=delete operate} 3 true true delete operate {ADD=add operate, DELETE=delete operate} ADD DELETE add operate,delete operate, ADD: add operate, DELETE: delete operate,