Task 1 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.1 HashMap — storing key-value pairs

Lesson

A dictionary of pairs

A HashMap stores key → value pairs, like a dictionary: each key maps to one value. Written Map<K, V>, it is generic in both the key type and the value type. Use put(key, value) to store a pair and get(key) to look the value up. Putting a key that already exists overwrites its value.


Worked example

Map<String, Integer> ages = new HashMap<String, Integer>();
ages.put("Ada", 30);
ages.put("Sam", 25);
System.out.println(ages.get("Ada"));   // 30
ages.put("Ada", 31);                    // overwrites
System.out.println(ages.get("Ada"));   // 31
System.out.println(ages.size());        // 2 — still two keys

The keys are unique; size() is the number of pairs.


▶ Try it: run this — two pairs are stored, then looked up by key.



A HashMap stores...


ages.put("Ada", 31) when "Ada" is already a key...


Type exactly what this program prints.

import java.util.HashMap;
import java.util.Map;
public class Main { public static void main(String[] a){
    Map<String, Integer> m = new HashMap<String, Integer>();
    m.put("x", 10);
    m.put("y", 20);
    m.put("x", 99);
    System.out.println(m.get("x"));
    System.out.println(m.size());
}}

To look up the value for a key, use...


True or false?