Define an object that can be used as a key in a HashMap.
Key objects must not change their state when they are used as keys in a HashMap. When an element is added to the HashMap, the element is placed into a bucket. The index of bucket is based on the hash code of the key. When looking up the key in the HashMap, the hash code of the key is used to search in only one bucket. This allows for reducing the number of key comparisons needed to find an element. Changing the fields of the key change the cache code without changing the bucket thus making it impossible to find the key in the HashMap. This situation is known as a key leak.
You can avoid this problem by making the key object immutable. An immutable key is an object that state cannot be changed after the object was created.
Use the Immutable Key pattern when
- accessing objects in a HashMap
An Immutable Key is an object that consists only of a constructor and getter methods.
- Immutable Key
- uniquely identifies an object in a HashMap
- a map that uses Immutable Key's hash code to place it in a bucket
- An application creates an Immutable Key and puts an element identified by the key in a HashMap. The HashMap uses Immutable Key's hash code to associate it with a bucket for fast access. The application uses the Immutable Key to retrieve the element identified by the key.
The immutable key pattern has the following benefits and drawbacks:
- It eliminates the possibility of the key leak. The application can safely use HashMap.
- It promotes concurrency. An immutable objects can be access by multiple threads without synchronization.
- It increases the number of classes in the system. In addition to a mutable class that contains fields that identify it, a separate class implementing the Immutable Key is need.
The following implementation issues are relevant to the Immuable Key pattern:
- Java supports declaring immutable field on the language level by proving the final modifier. A field declared as final can be assigned only once. A Java implementation of the Immutable Key pattern assigns final key object's fields in a constructor.