Lesson 2
Creating an Address Book Application Using Java HashMap
Creating an Application Using Java HashMap

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.

Introducing Methods to Implement

In this task, we will implement three methods to manage our address book:

  • AddContact(String phoneNumber, String name): Adds a new contact. Returns false if the contact already exists; otherwise, it adds the contact and returns true. 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 given phoneNumber. Returns null if the contact does not exist.
  • DeleteContact(String phoneNumber): Deletes a contact with the given phoneNumber. Returns true if the contact exists and is deleted, false otherwise.

Let's break down each method in detail in the following sections.

Step 1: Implementing AddContact

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:

Java
1import java.util.HashMap; 2import java.util.Map; 3 4class AddressBook { 5 private HashMap<String, String> contacts; 6 7 public AddressBook() { 8 contacts = new HashMap<>(); 9 } 10 11 public boolean addContact(String phoneNumber, String name) { 12 if (contacts.containsKey(phoneNumber)) { 13 return false; 14 } 15 contacts.put(phoneNumber, name); 16 return true; 17 } 18 19 public Map<String, String> getAllContacts() { 20 return contacts; 21 } 22} 23 24public class Solution { 25 public static void main(String[] args) { 26 AddressBook addressBook = new AddressBook(); 27 System.out.println(addressBook.addContact("123-456-7890", "Alice")); // True 28 System.out.println(addressBook.addContact("123-456-7890", "Bob")); // False 29 for (Map.Entry<String, String> contact : addressBook.getAllContacts().entrySet()) { 30 System.out.println(contact.getKey() + ": " + contact.getValue()); // 123-456-7890: Alice 31 } 32 } 33}

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 HashMap using contacts.put(phoneNumber, name); and return true.
Step 2: Implementing GetContact

This method retrieves the name associated with a given phoneNumber. If the contact does not exist, it returns null.

Question: What do we gain by returning null when a contact doesn't exist?

Answer: It provides a clear indicator that the contact is not in the address book, allowing us to handle such cases gracefully.

Here is the method implementation:

Java
1import java.util.HashMap; 2 3class AddressBook { 4 private HashMap<String, String> contacts; 5 6 public AddressBook() { 7 contacts = new HashMap<>(); 8 } 9 10 public boolean addContact(String phoneNumber, String name) { 11 if (contacts.containsKey(phoneNumber)) { 12 return false; 13 } 14 contacts.put(phoneNumber, name); 15 return true; 16 } 17 18 public String getContact(String phoneNumber) { 19 return contacts.get(phoneNumber); 20 } 21} 22 23public class Solution { 24 public static void main(String[] args) { 25 AddressBook addressBook = new AddressBook(); 26 addressBook.addContact("123-456-7890", "Alice"); 27 System.out.println(addressBook.getContact("123-456-7890")); // Alice 28 System.out.println(addressBook.getContact("098-765-4321")); // null 29 } 30}

In this method:

  • We use contacts.get(phoneNumber), which returns the name if the key exists; otherwise, it returns null.
Step 3: Implementing DeleteContact

This method deletes a contact with the given phoneNumber. If the contact exists and is deleted, it returns true. If the contact does not exist, it returns false.

Question: What could be a real-world consequence of not checking if the contact exists before deletion?

Answer: One consequence can be assuming that a contact was removed when, in fact, it was never there, leading to inaccurate tracking of records.

Here is the method implementation:

Java
1import java.util.HashMap; 2import java.util.Map; 3 4class AddressBook { 5 private HashMap<String, String> contacts; 6 7 public AddressBook() { 8 contacts = new HashMap<>(); 9 } 10 11 public boolean addContact(String phoneNumber, String name) { 12 if (contacts.containsKey(phoneNumber)) { 13 return false; 14 } 15 contacts.put(phoneNumber, name); 16 return true; 17 } 18 19 public String getContact(String phoneNumber) { 20 return contacts.get(phoneNumber); 21 } 22 23 public boolean deleteContact(String phoneNumber) { 24 return contacts.remove(phoneNumber) != null; 25 } 26 27 public Map<String, String> getAllContacts() { 28 return contacts; 29 } 30} 31 32public class Solution { 33 public static void main(String[] args) { 34 AddressBook addressBook = new AddressBook(); 35 addressBook.addContact("123-456-7890", "Alice"); 36 System.out.println(addressBook.deleteContact("123-456-7890")); // True 37 System.out.println(addressBook.deleteContact("098-765-4321")); // False 38 39 for (Map.Entry<String, String> contact : addressBook.getAllContacts().entrySet()) { 40 System.out.println(contact.getKey() + ": " + contact.getValue()); // Empty, as there are no contacts now 41 } 42 } 43}

In this method:

  • We use return contacts.remove(phoneNumber) != null;, which removes the entry if the key exists and returns true. If the key is not found, it returns false.
Summary

In this lesson, we explored creating a simple address book application using Java's HashMap. We implemented three key methods: addContact, getContact, and deleteContact to manage contacts effectively by focusing on adding, retrieving, and deleting entries. With the benefits of HashMaps, such as efficient operations and flexible key usage, we've demonstrated how to construct a robust address book application in Java. Great work! Now, let's proceed to the practice exercises to reinforce your understanding.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.