This week’s tutorial is taken from the textbook, exercises 5.25 – 30 on page 149. They are reproduced below.
The task is to implement a simple phone book where numbers are associated with names, both represented as strings. Your phone book should be able to add a new name/number pair and you should be able to lookup a number, given a name.
HashMap<String, String> phoneBook= new HashMap<String, String>();
initialises the phone book. The following statements add new entries:
phoneBook.put("Charles Nguyen", "(02) 9392 4587"); phoneBook.put("Lisa Jones", "(03) 4536 4674"); phoneBook.put("William H. Smith", "(07) 5488 0123");
Next, we look up an entry:
String number = phoneBook.get("Lisa Jones"); System.out.println(number);
We refer to the name as the key because it is used for the lookup. Given the above, answer the following questions. You will need to use the Java API documentation.
- Create a class MapTester in a new project. In it, use a HashMap to implement a phone book. You will have to import java.util.HashMap. In this class, implement two methods:
public void enterNumber(String name, String number)
and
public String lookupNumber(String name)
The methods should use put and get methods of the HashMap class to implement their functionality.
- What happens when you add an entry to a map with a key that already exists in the map?
- What happens when you add an entry to a map with two different keys?
- How do you check whether a given key is contained in a map? Try it in Java.
- What happens when you try to look up a values and the key does not exist in the map?
- How do you check how many entries are contained in the map?
No Comments so far ↓
Comments are closed.