14.7. Using Maps

As you saw at the beginning of this chapter, a map is a way of storing data that minimizes the need for searching when you want to retrieve an object. Each object is associated with a key that is used to determine where to store the reference to the object, and both the key and the object are stored in the map. Given a key, you can always go more or less directly to the object that has been stored in the map based on the key. It's important to understand a bit more about how the storage mechanism works for a map, and in particular what the implications of using the default hashing process are. You will explore the use of maps primarily in the context of the HashMap<> generic class type.

14.7.1. The Hashing Process

The implementation of a map in the Java collections framework provided by the HashMap<> class sets aside an array in which it will store key and object pairs. The index to this array is produced from the key object by using the hashcode for the object to compute an offset into the array for storing key/object pairs. By default, this uses the hashCode() method for the object that's used as a key. This is inherited in all classes from Object so this is the method that produces the basic hashcode unless the hashcode() method is redefined in the class for the key. The HashMap<> class doesn't assume that the basic hashcode is adequate. To try to ensure that the hashcode that is actually used has the characteristics required for an efficient map, the basic ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.