Welcome! Today, we will explore creating a simple address book application using Java's HashMap. This task will help you understand how to manipulate a HashMap in Java, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.
In this task, we will implement three methods to manage our address book:
addContact(String phoneNumber, String name): Adds a new contact. Returnsfalseif the contact already exists; otherwise, it adds the contact and returnstrue. For this task, let's assume names do not change, so it's not allowed to overwrite an existing contact's name.getContact(String phoneNumber): Retrieves the name for a givenphoneNumber. Returnsnullif the contact does not exist.deleteContact(String phoneNumber): Deletes a contact with the givenphoneNumber. Returnstrueif the contact exists and is deleted,falseotherwise.
Let's break down each method in detail in the following sections.
This method adds a new contact to the address book with the given phoneNumber and name. If the contact already exists, it returns false. Otherwise, it adds the contact and returns true.
Question: Why do you think we need to check if the contact already exists?
Answer: To avoid duplicating existing entries. Also, if a contact with the same phone number already exists, we shouldn't allow overwriting its name in this method, as it's only for creation.
Here is the method implementation:
In this method:
- We verify if the contact already exists using
if (contacts.containsKey(phoneNumber)). - If it exists, we return
false. - If it doesn't exist, we add it to our
HashMapusingcontacts.put(phoneNumber, name);and returntrue.
