Java Reference
In-Depth Information
• Formanyhashtables,aloadfactorof0.75isclosetooptimal.Thisvalueisthe
default for
HashMap
's hashtable implementation.
HashMap
supplies four constructors:
•
HashMap()
createsanew,emptyhashmapwithaninitialcapacityof16anda
load factor of 0.75.
•
HashMap(int initialCapacity)
creates a new, empty hashmap with
a capacity specified by
initialCapacity
and a load factor of 0.75. This
constructor throws
IllegalArgumentException
when
initialCa-
pacity
's value is less than 0.
•
HashMap(int initialCapacity, float loadFactor)
createsa
new, empty hashmap with a capacity specified by
initialCapacity
and
a load factor specified by
loadFactor
. This constructor throws
Illeg-
alArgumentException
when
initialCapacity
islessthan0orwhen
loadFactor
is less than or equal to 0.
•
HashMap(Map<? extends K, ? extends V> m)
creates a new
hashmap containing
m
's entries. This constructor throws
NullPointerEx-
ception
when
m
contains the null reference.
Listing 5-19
demonstrates a hashmap.
Listing 5-19.
Using a hashmap to count command-line arguments
import java.util.HashMap;
import java.util.Map;
class HashMapDemo
{
public static void main(String[] args)
{
Map<String, Integer> argMap = new HashMap<>();
for (String arg: args)
{
Integer count = argMap.get(arg);
argMap.put(arg, (count == null) ? 1 : count+1);
}
System.out.println(argMap);
System.out.println("Number of distinct arguments =