Java Collection: EnumMap - BunksAllowed

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

Community


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
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 + "]"; } }

Source code of TestMain.java
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()); } } }


Happy Exploring!

No comments:

Post a Comment

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