<pre>public class MapTester { // instance variables - replace the example below with your own private HashMap<String, String> contacts; /** * Constructor for objects of class MapTester */ public MapTester() { contacts = new HashMap<String, String>(); } /** * Enter the given pair into the HashMap. * @param name A contact name (the key). * @param number The contact's phone number (as a string) (the value). */ public void enterNumber(String name, String number) { contacts.put(name, number); } /** * Look up the given name in the map and return the associated number. * @param name The name to be looked up (the key) * @return The assoicated number, if any (the value). */ public String lookUpNumber(String name) { return null; } }
public String lookUpNumber(String name) { String number; // option 1 - first check if the key exists if (contacts.containsKey(name) { number = (String)contacts.get(name); } // option 2 - get the value in the map or some default value number = (String)contacts.getOrDefault(name, "NoName"); // option 3 - just use get which returns null if the key does not exist number = (String)contacts.get(name); // return whatever value was found return number; }
HashMap
if
HashMap.get
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)