Java EnumMap Initialize
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)
EnumMap
with examples.
Using Class Object
To create an enum map by specifiedClass
object, use following constructor.
public EnumMap(Class<K> keyType)
NullPointerException
will be thrown.
Now find the example.
Find a sample enum.
enum MyEnum { A, B, C, D, E, F }
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);
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 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);
{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 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);
{A=AA, B=BB, C=CC, D=DD}