Java Reference
In-Depth Information
60
System.out.printf(
61
"%nsize: %d%nisEmpty: %b%n" ,
map.size() map.isEmpty()
,
);
62
}
63
} // end class WordTypeCount
Enter a string:
this is a sample sentence with several words this is another sample
sentence with several different words
Map contains:
Key Value
a 1
another 1
different 1
is 2
sample 2
sentence 2
several 2
this 2
with 2
words 2
size: 10
isEmpty: false
Fig. 16.18 | Program counts the number of occurrences of each word in a String . (Part 3 of 3.)
Line 14 creates an empty HashMap with a default initial capacity (16 elements) and a
default load factor (0.75)—these defaults are built into the implementation of HashMap .
When the number of occupied slots in the HashMap becomes greater than the capacity
times the load factor, the capacity is doubled automatically. HashMap is a generic class that
takes two type arguments—the type of key (i.e., String ) and the type of value (i.e.,
Integer ). Recall that the type arguments passed to a generic class must be reference types,
hence the second type argument is Integer , not int .
Line 16 calls method createMap (lines 21-44), which uses a Map to store the number of
occurrences of each word in the sentence. Line 25 obtains the user input, and line 28 token-
izes it. Lines 31-43 convert the next token to lowercase letters (line 33), then call Map
method containsKey (line 36) to determine whether the word is in the map (and thus has
occurred previously in the string). If the Map does not contain the word, line 42 uses Map
method put to create a new entry, with the word as the key and an Integer object con-
taining 1 as the value. Autoboxing occurs when the program passes integer 1 to method put ,
because the map stores the number of occurrences as an Integer . If the word does exist in
the map, line 38 uses Map method get to obtain the key's associated value (the count) in the
map. Line 39 increments that value and uses put to replace the key's associated value.
Method put returns the key's prior associated value, or null if the key was not in the map.
Error-Prevention Tip 16.2
Always use immutable keys with a Map . The key determines where the corresponding value
is placed. If the key has changed since the insert operation, when you subsequently attempt
to retrieve that value, it might not be found. In this chapter's examples, we use String s
as keys and String s are immutable.
 
Search WWH ::




Custom Search