Java Reference
In-Depth Information
Suppose you intended to use a
Person
object as a key in a hash table, and the class data members were
firstName
and
surname
of type
String
, and
age
of type
int
. You could implement the
hashCode()
method for the class as:
public int hashCode() {
return 13*firstName.hashCode() + 17*surname.hashCode() + 19*age;
}
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 hash code for the key class.
Creating a HashMap
As we saw, all map classes implement the
Map
interface, so an object of any map class can be
referenced using a variable of type
Map
. We will look in detail at the
HashMap
class since it is good for
most purposes. There are four constructors you can use to create a
HashMap
object:
Constructor
Description
HashMap()
Creates a map with the capacity to store a default number of
objects. The default capacity is 101 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 specify in the argument and a default load factor of 0.75.
HashMap(int capacity,
float loadFactor)
Creates a hash table with the capacity and load factor that you
specify.
HashMap(Map map)
Creates a map with the capacity and load factor of the
Map
object passed as an argument.
To create a map using the default constructor, you can write something like this:
HashMap theMap = new HashMap();
The
capacity
for a map is simply the number of key/object pairs it can store. The capacity increases
automatically as necessary, but this is a relatively time consuming operation. The capacity value of the
map is combined with the hash code for the key that you specify to compute the index that determines
where an object 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 = 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. There must always be spare capacity in a map for efficient operation. With
too little spare capacity, there is an increased likelihood that keys will generate the same table index, so
collisions become more likely.