Welcome! Today, we're exploring the dynamic world of HashMaps in Java. It's part of the Java Collections framework, designed for efficient data storage and retrieval. Imagine a HashMap as a locker system in a spaceship, where each locker (i.e., a key) can store an item (i.e., a value). In this lesson, we'll construct a HashMap, add key-value pairs, access elements, and understand the basic properties and methods.
Ready? Let's go!
Creating a HashMap involves declaring its data type and initializing it. Just like an ArrayList, HashMaps can only hold object types. Here's a HashMap that maps our spaceship crew's names (String) to their ages (Integer).
The HashMap is empty for now, represented by {}.
In our spaceship, different crew members have different roles. These roles can be linked to the crew members' ages.
Adding entries to a HashMap is done with put(key, value). If put() is used with an already existing key, the old value gets replaced. remove(key) allows us to exclude entries from our HashMap.
Accessing a HashMap involves using the get(key) method with a unique key. This method returns the value for the specified key or null if there is no value stored for this key. For cases when you need some other default value rather than null, you can use getOrDefault(key, default) that returns a default value if the key doesn't exist.
Let's see how we can retrieve the engineer's age:
You can see that get() for the existent key returned just the value, while for the non-existent key "Artist", it returned null. In the meantime, getOrDefault() returned the default value 0 that we provided as a parameter.
