The Map
This chapter is about maps. A map is a collection of key–value pairs with distinct keys and no order, and it looks up the value stored under a given key.
After reading this chapter, you should be able to:
- Specify the Map ADT’s contract: what
putreturns when the key is already present, whatgetreturns for an absent key, and whynullvalues are rejected - Implement a map as a linked list (
LinkedMap) and as an unsorted array of entries (ArrayMap) - Trace a sequence of map operations on
LinkedMapandArrayMap, telling aputthat inserts a new key from one that overwrites a value - Compare the two implementations in time and memory, including why linear search keeps
get,put, andremoveat in both - Explain why a key must not change after it is stored, which makes immutable keys such as
Stringthe safe choice - Make a map iterable over its keys by having
MapextendIterable<K>and writing the key iterator for each implementation - Implement an
entries()traversal that visits every key–value pair in , instead of the of callinggetinside a key loop - Design a read-only
Map.Entryinterface that lets a caller read a stored key and value but not change the map’s internals
You can download the accompanying code for this chapter: starter and solution.
Sections
- Storing a Password
- The Map ADT
- Map ADT Specification
- Using a Linked List to Implement a Map
- The LinkedMap Class
- Implementing get, containsKey, put, and remove
- Tracing the LinkedMap
- Using an Array to Implement a Map
- The ArrayMap Class
- Implementing get, containsKey, put, and remove
- Tracing the ArrayMap
- Keys Must Not Change
- Iterating a Map
- Returning the Stored Entries
- Why Not Return the Stored Object
- The Map.Entry Interface
- Iterating the Entries