Java Reference
In-Depth Information
Exercise 5.28 What happens when you add an entry to a map with two different keys?
Exercise 5.29 How do you check whether a given key is contained in a map? (Give a Java
code example.)
Exercise 5.30 What happens when you try to look up a value and the key does not exist in
the map?
Exercise 5.31 How do you check how many entries are contained in a map?
Exercise 5.32 How do you print out all keys currently stored in a map?
Using a map for the TechSupport system
In the TechSupport system, we can make good use of a map by using known words as keys and as-
sociated responses as values. Code 5.4 shows an example in which a HashMap named response-
Map is created and three entries are made. For example, the word “slow” is associated with the text
“I think this has to do with your hardware. Upgrading your processor should solve all
performance problems. Have you got a problem with our software?”
Now, whenever somebody enters a question containing the word “slow,” we can look up and
print out this response. Note that the response string in the source code spans several lines but
is concatenated with the + operator, so a single string is entered as a value into the HashMap .
Code 5.4
Associating selected
words with possible
private HashMap<String, String> responseMap;
public Responder()
responseMap = new HashMap<String, String>();
* Enter all the known keywords and their associated
* responses into our response map.
private void fillResponseMap()
responseMap.put( "slow" ,
"I think this has to do with your hardware. \n" +
"Upgrading your processor should solve all " +
"performance problems. \n" +
"Have you got a problem with our software?" );
responseMap.put( "bug" ,
Search WWH ::

Custom Search