Maps
A map is an object that stores associations between keys and values, or key/value pairs.
Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated.
Map doesn't implement the Iterable interface.
The Map Interfaces
The following interfaces support maps:
Interface | Description |
---|---|
Map | Maps unique keys to values. |
Map.Entry | Describes an element (a key/value pair) in a map. This is an inner class of Map. |
NavigableMap | Extends SortedMap to handle the retrieval of entries based on closest-match searches. |
SortedMap | Extends Map so that the keys are maintained in ascending order. |
The Map Interface
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object.
Map is generic and is declared as shown here:
interface Map<K, V>
- K specifies the type of keys.
- V specifies the type of values.
SortedMap Interface
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending order based on the keys.
SortedMap is generic and is declared as shown here:
interface SortedMap<K, V>
- K specifies the type of keys.
- V specifies the type of values.
NavigableMap Interface
The NavigableMap interface extends SortedMap and declares the behavior of a map that supports the retrieval of entries based on the closest match to a given key or keys.
NavigableMap is a generic interface that has this declaration:
interface NavigableMap<K,V>
- K specifies the type of the keys
- V specifies the type of the values associated with the keys.
The Map.Entry Interface
The Map.Entry interface enables you to work with a map entry.
The entrySet( ) method from Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object. Map.Entry is generic and is declared like this:
interface Map.Entry<K, V>
- K specifies the type of keys
- V specifies the type of values.
Map Classes
Several classes provide implementations of the map interfaces.
Class | Description |
---|---|
AbstractMap | Implements most of the Map interface. |
EnumMap | Extends AbstractMap for use with enum keys. |
HashMap | Extends AbstractMap to use a hash table. |
TreeMap | Extends AbstractMap to use a tree. |
WeakHashMap | Extends AbstractMap to use a hash table with weak keys. |
LinkedHashMap | Extends HashMap to allow insertion-order iterations. |
IdentityHashMap | Extends AbstractMap and uses reference equality when comparing documents. |
AbstractMap is a superclass for all concrete map implementations.
WeakHashMap implements a map that uses "weak keys". WeakHashMap allows an element in a map to be garbage-collected when its key is otherwise unused.