Create a class MapTester. In it, use a HashMap to implement a phone book. In thi
ID: 3770536 • Letter: C
Question
Create a class MapTester. In it, use a HashMap to implement a phone book. In this class implement two methods:
public void enterNumber(String name, String number)
and
public String lookupNumber(String name)
The methods should use the put and get methods of the HashMap class to implement their functionality.
The following code fragment creates a HashMap and inserts three entries into it.
HashMap phoneBook = new HashMap();
phoneBook.put("Charles Nguyen", "(531) 9392 4587");
phoneBook.put("Lisa Jones", "(402) 4536 4674");
phoneBook.put("William H. Smith", "(998) 5488 0123");
Include the code above in the constructor
Explanation / Answer
import static org.junit.Assert.*;
import org.junit.Test;
import static koan.Constants.*;
import java.util.*;
public class HashMap
{
public void checkHowManyEntries()
{
HashMap<String,String> phoneBook = new HashMap<String,String>();
phoneBook.put("Charles Nguyen","(531) 9392 4587");
phoneBook.put("Lisa Jones","(402) 4536 4674");
phoneBook.put("William H. Smith","(998) 5488 0123");
assertEquals("this map has 3 entries",3,phoneBook.size());
}
public void addKeyThatAlreadyExists()
{
HashMap<String,String> phoneBook = new HashMap<String,String>();
phoneBook.put("Charles Nguyen","(531) 9392 4587");
phoneBook.put("Lisa Jones","(402) 4536 4674");
phoneBook.put("William H. Smith","(998) 5488 0123");
phoneBook.put("Lisa Jones","new phonenumber");
assertEquals("now the map has 3 entries",3,phoneBook.size());
assertEquals("existing entry is overwritten","new phonenumber",phoneBook.get("Lisa Jones"));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.