Java EnumMap Class: A Beginner's Guide
Introduction
Hello there, future Java programmers! Today, we're going to embark on an exciting journey into the world of Java's EnumMap class. Now, I know what you might be thinking: "EnumMap? That sounds complicated!" But don't worry! By the end of this tutorial, you'll be using EnumMaps like a pro, and you might even have a little fun along the way.
Let's start with a simple analogy. Imagine you have a special drawer for each day of the week to organize your socks. That's essentially what an EnumMap is – a way to organize data using enum constants as keys. Cool, right? Let's dive in!
Class Declaration
First things first, let's look at how we declare an EnumMap:
import java.util.EnumMap;
enum DaysOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
EnumMap<DaysOfWeek, String> activities = new EnumMap<>(DaysOfWeek.class);
In this example, we're creating an EnumMap that uses our DaysOfWeek
enum as keys and String
values to store activities. The DaysOfWeek.class
part tells Java which enum we're using for our keys.
Class Constructors
EnumMap has three constructors. Let's look at each one:
-
EnumMap(Class
keyType) EnumMap<DaysOfWeek, String> activities = new EnumMap<>(DaysOfWeek.class);
This creates an empty EnumMap with keys of the specified enum type.
-
EnumMap(EnumMap<K,? extends V> m)
EnumMap<DaysOfWeek, String> activitiesCopy = new EnumMap<>(activities);
This creates an EnumMap with the same key type as the specified EnumMap and initializes it with the same mappings (if any).
-
EnumMap(Map<K,? extends V> m)
Map<DaysOfWeek, String> regularMap = new HashMap<>(); regularMap.put(DaysOfWeek.MONDAY, "Gym"); EnumMap<DaysOfWeek, String> activitiesFromMap = new EnumMap<>(regularMap);
This creates an EnumMap initialized from a regular Map.
Class Methods
Now, let's look at some of the most commonly used methods in EnumMap:
Method | Description |
---|---|
put(K key, V value) | Associates the specified value with the specified key |
get(Object key) | Returns the value associated with the specified key |
remove(Object key) | Removes the mapping for this key if present |
size() | Returns the number of key-value mappings |
clear() | Removes all mappings from this map |
containsKey(Object key) | Returns true if this map contains a mapping for the specified key |
containsValue(Object value) | Returns true if this map maps one or more keys to the specified value |
Let's see these methods in action:
EnumMap<DaysOfWeek, String> activities = new EnumMap<>(DaysOfWeek.class);
// Adding key-value pairs
activities.put(DaysOfWeek.MONDAY, "Gym");
activities.put(DaysOfWeek.TUESDAY, "Cinema");
// Getting a value
String mondayActivity = activities.get(DaysOfWeek.MONDAY);
System.out.println("Monday's activity: " + mondayActivity);
// Checking if a key exists
boolean hasWednesday = activities.containsKey(DaysOfWeek.WEDNESDAY);
System.out.println("Has Wednesday: " + hasWednesday);
// Removing a key-value pair
activities.remove(DaysOfWeek.TUESDAY);
// Getting the size
int size = activities.size();
System.out.println("Number of activities: " + size);
// Clearing the map
activities.clear();
In this example, we're adding activities for different days, retrieving values, checking for keys, removing entries, and finally clearing the entire map. It's like organizing and reorganizing our sock drawer!
Methods Inherited
EnumMap inherits methods from its parent classes. Here are some useful ones:
Method | Inherited From | Description |
---|---|---|
clone() | AbstractMap | Creates a shallow copy of this map |
equals(Object o) | AbstractMap | Compares the specified object with this map for equality |
hashCode() | AbstractMap | Returns the hash code value for this map |
toString() | AbstractMap | Returns a string representation of this map |
Adding a Key-Value to an EnumMap Of Enum, Integer Pair Example
Now, let's try something a bit more complex. We'll create an EnumMap that uses an enum as keys and integers as values:
enum Fruit { APPLE, BANANA, ORANGE, MANGO }
EnumMap<Fruit, Integer> fruitPrices = new EnumMap<>(Fruit.class);
// Adding key-value pairs
fruitPrices.put(Fruit.APPLE, 100);
fruitPrices.put(Fruit.BANANA, 80);
fruitPrices.put(Fruit.ORANGE, 120);
fruitPrices.put(Fruit.MANGO, 150);
// Printing the EnumMap
System.out.println("Fruit Prices: " + fruitPrices);
// Updating a value
fruitPrices.put(Fruit.BANANA, 90);
// Getting a specific value
int applePrice = fruitPrices.get(Fruit.APPLE);
System.out.println("Price of Apple: " + applePrice);
// Iterating over the EnumMap
for (Map.Entry<Fruit, Integer> entry : fruitPrices.entrySet()) {
System.out.println(entry.getKey() + ": $" + entry.getValue());
}
In this example, we're creating a fruit price list. We add prices for different fruits, update the price of bananas, retrieve the price of apples, and then iterate over the entire map to print all fruit prices.
And there you have it! You've just learned the basics of Java's EnumMap class. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Who knows? You might just find yourself organizing your entire life with EnumMaps! (Just kidding, but they are pretty useful.)
Happy coding, and may your EnumMaps always be well-organized!
Credits: Image by storyset