什么是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,
?
本文轉自風一樣的碼農博客園博客,原文鏈接:http://www.cnblogs.com/chenpi/p/5296330.html,如需轉載請自行聯系原作者