Java Reference
In-Depth Information
}
Wherever a data member is an object of another class rather than a variable of one of the basic types, you
need to implement the
hashCode()
method for that class. You can then use that in the computation of the
hashcode for the key class.
Creating a HashMap Container
As you saw earlier in this chapter, all map classes implement the
Map<>
interface, so an object of any map
class can be referenced using a variable of type
Map<>
. You look in detail at the
HashMap<>
class because it
is good for most purposes. There are four constructors to create a
HashMap<K,V>
object:
•
HashMap()
creates a map with the capacity to store a default number of objects. The default capa-
city is 16 objects, and the default load factor (more on the load factor below) is 0.75.
•
HashMap(int capacity)
creates a map with the capacity to store the number of objects you spe-
cify in the argument and a default load factor of 0.75.
•
HashMap(int capacity,float loadFactor)
creates a map with the capacity and load factor
that you specify.
•
HashMap(Map<? extends K, ? extends V> map)
creates a map with the mappings, capacity
and load factor of the
Map
object passed as the argument.
To create a map using the default constructor, you can write something like this:
HashMap<String,Person> theMap = new HashMap<>();
This statement creates a
HashMap<>
object that can store
Person
objects with associated keys of type
String
.
The
capacity
for a map is simply the number of key/object pairs it can store. The capacity increases auto-
matically as necessary, but this is a relatively time-consuming operation. The capacity value of the map is
combined with the hashcode for the key that you specify to compute the index that determines where an ob-
ject and its key are to be stored. To make this computation produce a good distribution of index values, you
should ideally use prime numbers for the capacity of a hash table when you specify it yourself. For example:
HashMap myMap<String,Person> = new HashMap<>(151);
This map has a capacity for 151 objects and their keys, although the number of objects stored can never
actually reach the capacity. You must always have spare capacity in a map for efficient operation. With too
little spare capacity, you have an increased likelihood that keys generate the same bucket index, so collisions
become more likely.
The
load factor
is used to decide when to increase the size of the hash table. When the size of the table
reaches a value that is the product of the load factor and the capacity, the capacity is increased automatically
to twice the old capacity plus one — the plus one ensuring it is at least odd, if not prime. The default load
factor of 0.75 is a good compromise, but if you want to reduce it you could do so by using the third con-
structor:
// Create a map with a 60% load factor
HashMap<String,Person> aMap = new HashMap<>(151, 0.6f);