Course Content
Introduction to Java
In our previous chapter, we learned about ArrayList. Today we will learn about Hashmaps, another beneficial element in the Java Collections Framework.
What is a HashMap?
HashMap
is like a big box where you can store things and quickly find them later.
Imagine you're organizing an extensive library and want to keep track of all the books you have in stock. You could use a HashMap
to store the information about each book. The key could be the book's title, and the value could be the number of copies of the book you have in stock.
Creating a HashMap?
Here's how you could create a HashMap
in Java to keep track of your books:
Main.java
In this example, we're creating a HashMap called library. The two parts in the angle brackets, <String, Integer>
, tell Java what information we want to store in the HashMap
. The first type, String, represents the key - this is like the book's title. The second type, Integer, represents the value - this is like the number of copies of the book we have in stock.
Adding elements to HashMap
Now that we have our library catalog, we can start adding books to it! Here's how:
Main.java
In this example, we're adding three books to our library catalog: "To Kill a Mockingbird"
, "The Great Gatsby"
, and "Pride and Prejudice"
. We're using the put method to add the books to the HashMap
, giving it two pieces of information: the key (the book's title) and the value (the number of copies we have in stock).
Searching for a value in HashMap
What if we want to check how many copies of "To Kill a Mockingbird"
we have? We can easily find that information using the key:
Main.java
In this example, we're using the get method to retrieve the value associated with the key "To Kill a Mockingbird"
. We're storing the result in a variable called numCopies, and then printing it out to the console.
Updating a value in HashMap
Let's imagine we just got 10 more copies of "To Kill a Mockingbird". We can update the HashMap like this:
Main.java
In this example, we're using the put method to update the value associated with the key "To Kill a Mockingbird". We're retrieving the original value with the library.get("To Kill a Mockingbird")
, add 10 to it, and then store the result in the HashMap
with the put method.
Conclusion
HashMaps
are very useful in many programs, including library management systems. They allow you to store and retrieve information quickly and easily, and they're a great tool to have in your programming toolbox!
What is a HashMap in Java?
Select the correct answer
How do you add values to a HashMap in Java?
Select the correct answer
Section 4.
Chapter 5