Java Reference
In-Depth Information
The put method inserts an entry into the map, and get retrieves the value for a given key. The
following code fragment creates a HashMap and inserts three entries into it. Each entry is a key/
value pair consisting of a name and a telephone number.
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");
As we saw with ArrayList , when declaring a HashMap variable and creating a HashMap ob-
ject, we have to say what type of objects will be stored in the map and, additionally, what type
of objects will be used for the key. For the phone book, we will use strings for both the keys and
the values, but the two types will sometimes be different.
As we have seen in Section 4.4.2 if we are using Java 7 (or newer), the generic type specifica-
tion on the right-hand side of the assignment may be left out, like this:
HashMap<String, String> phoneBook = new HashMap<>();
This is known as the “diamond operator” because of the two empty angle brackets: <> .
In Java 7, this line is equivalent to the first line above (but in Java 6 it does not compile). If you leave
out the generic parameters, the compiler will just assume the same parameters used on the left-hand
side of the assignment. Thus, the effect is exactly the same—we just save a little bit of typing.
The following code will find the phone number for Lisa Jones and print it out.
String number = phoneBook.get("Lisa Jones");
Note that you pass the key (the name “Lisa Jones”) to the get method in order to receive the
value (the phone number).
Read the documentation of the get and put methods of class HashMap again and see whether
the explanation matches your current understanding.
Exercise 5.25 How do you check how many entries are contained in a map?
Exercise 5.26 Create a class MapTester (either in your current project or in a new project).
In it, use a HashMap to implement a phone book similar to the one in the example above.
(Remember that you must import java.util.HashMap .) In this class, implement two methods:
public void enterNumber(String name, String number)
public String lookupNumber(String name)
The methods should use the put and get methods of the HashMap class to implement their
Exercise 5.27 What happens when you add an entry to a map with a key that already ex-
ists in the map?
Search WWH ::

Custom Search