Maps

A key is found in constant time; order is not a promise.

A Map stores key-value pairs. HashMap finds a key quickly and does not promise an iteration order. If you need insertion order, use LinkedHashMap. Keys are looked up through equals and hashCode. For String they are already written. For your own class without these methods, the map behaves like a comparison of references.

get returns null both when the key is missing and when the key holds a null value. If that matters, ask containsKey. In the training example, a missing person is the string none, not a null handed outside: comparing text is simpler for the caller.

Do not use a mutable object as a key if you change its fields later. The map's bucket depends on the hash at the moment of put. Change a field and the key gets "lost" in another bucket. Strings and records are safe here; lists as keys almost never are.

One key, one value. A second put replaces the old one. That is handy for a settings map and dangerous if you thought you were collecting a list. For a list of values there is Map<String, List<...>>, and it is easy to forget to initialize it.

Practice

  1. No key

    What does HashMap.get return if the key is missing and you never stored null?

    • an empty string
    • null
    • 0
    • always an exception
  2. A second put

    Riga was put under the key Ann, then Rome was put under the same key. What does get("Ann") return?

  3. City by name

    Write static String city(String name). The map holds only Ann -> Riga. For Ann return Riga, otherwise none.