Java Reference
In-Depth Information
FIGURE 14-3
A key can be any kind of object that you want to use to reference the stored objects. Because a key has to
uniquely identify an object, all the keys in a map must be different. To put this in context, suppose you were
creating a program to provide an address book. You might store all the details of each person — the name,
address, phone number, or whatever — in a single object of type Entry , perhaps, and store a reference to the
object in a map. The key is the mechanism for retrieving objects, so assuming that all names are different, a
person's name is a natural choice for the key. Thus the entries in the map in this case would be Name / Entry
pairs. You would supply a Name object as the key and get back the Entry object corresponding to the key,
which might encapsulate data such as the address and/or the phone number. You might also have another
map in this application where entries were keyed on the phone number. Then you could retrieve an entry
corresponding to a given number. Of course, in practice, names are not unique — hence, the invention of
such delightful attachments to the person as Social Security numbers.
Hashing
Where a key/object pair is stored in a map is determined from the key by a process known as hashing . Hash-
ing processes the key object to produce an integer value called a hashcode . A basic requirement for hashing
is that you get the same hashcode from repeatedly hashing the same object.
The hashCode() method that is defined in the Object class produces a hashcode of type int for an
object based on the object's location in memory. The hashcode for a key is typically used to calculate an
offset from the start of the memory that has been allocated within the map for storing objects, and the offset
determines the location where the key/object pair is stored.
Ideally the hashing process should result in values that are uniformly distributed within a given range,
and every key should produce a different hashcode. In general, this may not be the case. However, there
are ways of dealing with hashcodes that don't turn out to be ideal, so it is not a major problem. The im-
plementations for map collections usually have provision for dealing with the situation where two or more
 
Search WWH ::




Custom Search