Java Collection: EnumMap - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

It is a specialized implementation of the Map interface for enumeration data types.

A few important facts about EnumMap are as follows:

  1. It is not synchronized.
  2. It is an ordered collection.
  3. It is much faster than HashMap.
  4. All keys must be keys of a single enum type.
  5. It doesn't allow a null key, though null values are permitted.

Hierarchy of EnumMap class


It extends AbstractMap and implements Map Interface in Java.

Source code of Item.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Source code of TestMain.java
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
package com.t4b.test;
import java.util.EnumMap;
import java.util.Map;
public class TestMain {
public enum WeekDays {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
};
public static void main(String[] args) {
EnumMap<WeekDays, Item> foodhabbit = new EnumMap<WeekDays, Item>(WeekDays.class);
foodhabbit.put(WeekDays.Monday, new Item("Apple", 1, 150.0));
foodhabbit.put(WeekDays.Tuesday, new Item("Grape", 2, 250.0));
foodhabbit.put(WeekDays.Wednesday, new Item("Mango", 3, 10));
foodhabbit.put(WeekDays.Thursday, new Item("Pine Apple", 4, 100));
foodhabbit.put(WeekDays.Friday, new Item("Grape", 2, 250.0));
foodhabbit.put(WeekDays.Saturday, new Item("Pine Apple", 4, 100));
foodhabbit.put(WeekDays.Sunday, new Item("Apple", 1, 150.0));
for (Map.Entry item : foodhabbit.entrySet()) {
System.out.println(item.getKey() + " : " + item.getValue());
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.