Home  >  Core Java

Java EnumMap Initialize

By Arvind Rai, September 11, 2021
On this page we will learn initializing Java EnumMap in our application.
1. Java EnumMap is a specialized Map implementation whose key is of Enum type.
2. All keys in EnumMap must be of a single Enum type while creating it.
3. The elements in EnumMap are maintained in the natural order of keys.
4. Null keys are not permitted whereas null values are permitted in EnumMap.
5. The EnumMap has following constructors to initialize it.
EnumMap(Class<K> keyType)
EnumMap(EnumMap<K,? extends V> m)
EnumMap(Map<K,? extends V> m) 
Now we will discuss initializing EnumMap with examples.



Using Class Object

To create an enum map by specified Class object, use following constructor.
public EnumMap(Class<K> keyType) 
It creates an empty enum map with the specified key type. If keyType is null, then NullPointerException will be thrown.
Now find the example.
Find a sample enum.
enum MyEnum {
  A, B, C, D, E, F
} 
Find the code to initialize EnumMap by passing Class object of above enum.
EnumMap<MyEnum, String> em = new EnumMap<MyEnum, String>(MyEnum.class);
System.out.println(em.size()); // 0
em.put(MyEnum.A, "AA");
em.put(MyEnum.B, "BB");
System.out.println(em.size()); // 2
System.out.println(em); 
Output:
0
2
{A=AA, B=BB} 

Using EnumMap

To create an enum map with the specified enum map, find the following constructor.
public EnumMap(EnumMap<K,? extends V> m) 
The newly created enum map will contain all the elements of the enum map, m, from which we initialize our enum map.
The newly created enum map will have same key type as of specified enum map.
If enum map, m, has size zero, then newly created enum map will also has size zero.
If enum map, m, is null, then NullPointerException is thrown.
Example:
EnumMap<MyEnum, String> em1 = new EnumMap<MyEnum, String>(MyEnum.class);
em1.put(MyEnum.A, "AA");
em1.put(MyEnum.B, "BB");
EnumMap<MyEnum, String> em2 = new EnumMap<MyEnum, String>(em1);
em2.put(MyEnum.C, "CC");
em2.put(MyEnum.D, "DD");
System.out.println(em2); 
Output
{A=AA, B=BB, C=CC, D=DD} 

Using Map

To create an enum map by specified map, find the constructor.
public EnumMap(Map<K,? extends V> m) 
The specified map must contain at least one mapping to decide key type of new enum map.
The newly created enum map will contain the elements of specified map.
If specified map, m, contains no mapping, then IllegalArgumentException is thrown.
If specified map, m, is null, then NullPointerException is thrown.
Example:
Map<MyEnum, String> map = new HashMap<MyEnum, String>();
map.put(MyEnum.A, "AA");
map.put(MyEnum.B, "BB");
EnumMap<MyEnum, String> em = new EnumMap<MyEnum, String>(map);
em.put(MyEnum.C, "CC");
em.put(MyEnum.D, "DD");    
System.out.println(em); 
Output
{A=AA, B=BB, C=CC, D=DD} 

Reference

Class EnumMap
POSTED BY
ARVIND RAI
ARVIND RAI











©2021 concretepage.com | Privacy Policy | Contact Us