EnumMap


  • EnumMap birth is in java 1.5.
  • EnumMap extends AbstractMap class.
  • EnumMap implements Serializable, Cloneable.
  • It is specialised Map implementation to use with enum type keys.
  • All the keys in an EnumMap must belong to the single enum type that is specified when the EnumMap is created.
  • Internally EnumMap are represented as arrays.
  • EnumMaps representation is very efficient and compact.
  • EnumMaps are maintained in the natural order of their keys
  • (the order in which the enum constants are declared).
  • The Iterator returned by the EnumMap are weakly consistent.
  • The Iterator will never throw ConcurrentModificationException.
  • EnumMap may or may not have the change effects of any modifications to the EnumMap made while the iteration is in progress.
  • Null keys are not permitted. 
  • Null values are permitted.
  • Attempt to insert a null key will throw NullPointerException. 
  • EnumMap is not synchronized.
  • All the basic operations (put,get,delete) are execute in constant time. 
  • All operations are likely (though it is not guaranteed) to be more faster than HashMap.
Example




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.EnumMap;
import java.util.Iterator;
import java.util.Map;

public class EnumMapTest {

    enum WeekDay{
        SUNDAY,MONDAY, TUESDAY, WEDNESDAY;
    }

    public static void main(String args[]){

        EnumMap<WeekDay,String> enumMap =  new EnumMap<WeekDay, String>(WeekDay.class);

        enumMap.put(WeekDay.SUNDAY,"Sunday");        enumMap.put(WeekDay.MONDAY,"Monday");
        Iterator<Map.Entry<WeekDay,String>> iterator = enumMap.entrySet().iterator();

        while(iterator.hasNext()){

            Map.Entry<WeekDay,String> entry = iterator.next();

            WeekDay key = entry.getKey();

            String value = entry.getValue();

            System.out.println("Key: "+key+", Value: "+value);

        }
    }
}