Problem overview
The method addContact receives a phone book phoneBook, a HashMap from names to phone numbers, plus a name and a number. It adds the name with its number and returns the phone book, but only when the name is not in the book yet. A name that is already there keeps its old number. The phone book may be empty, and the order of entries does not matter.
For a book with Ana and Ben and the new name Cara, Cara is added. For the name Ben with a new number, nothing changes, and Ben keeps 555-0199. For an empty book and Max, the book gets one contact.
Approach
The catch is what put does with an existing key: it replaces the old value. So calling put straight away would overwrite Ben's number, which the task forbids. The fix is to ask first. phoneBook.containsKey(name) is true when the name is already a key, so !phoneBook.containsKey(name) is true only for a new name. Only then do we put.
Step by step
- Write the check
if (!phoneBook.containsKey(name))and close its braces. For a name already in the book, nothing should happen. - Inside it,
putthe name with its number. On a new key,putadds the entry. - After the
if, returnphoneBook: with the new contact, or as it was.
The solution in Java
class Solution {
public HashMap<String, String> addContact(HashMap<String, String> phoneBook, String name, String number) {
if (!phoneBook.containsKey(name)) {
phoneBook.put(name, number);
}
return phoneBook;
}
}
Details worth knowing:
- The method changes the map it receives and returns that same map.
- Both the keys (names) and the values (numbers) are
Strings here. - Numbers are never checked for duplicates, because two people may share a number. Only the key matters.
Edge cases and common mistakes
- Calling put without the check.
phoneBook.put("Ben", "555-0100")silently replaces Ben's number: the map then holds{Ben=555-0100}for that key. - Forgetting the
!. Without it, the code only touches names that already exist, and new names are never added. - Checking the number instead of the name. The key is the name, so
containsKey(number)asks the wrong question. - Empty book.
containsKeyon an empty map isfalse, so the contact is added.
Why not always put?
It might seem simpler to call put every time. The difference only shows for a name that is already there, and that is the case the task singles out: put replaces the number, and the task says the old one stays. The containsKey check is the whole difference between "add a contact" and "add or overwrite a contact".
Testing
Results, printed as key: value lines sorted by key, as the lesson's tests print them:
- Ana
555-0142, Ben555-0199, name Cara, number555-0123gives Ana: 555-0142, Ben: 555-0199, Cara: 555-0123. - The same book with name Ben and number
555-0100gives Ana: 555-0142, Ben: 555-0199. - An empty book with Max and
555-0100gives Max: 555-0100.
