Task 3 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 — checking keys safely

Lesson

What if the key is missing?

Calling get on a key that is not in the map returns null — which can cause errors if you are not careful. Two safe tools: containsKey(key) returns true/false, and getOrDefault(key, fallback) returns the value if present, or the fallback if not.


Worked example

Map<String, Integer> ages = new HashMap<String, Integer>();
ages.put("Ada", 30);

System.out.println(ages.get("Bo"));               // null — missing key
System.out.println(ages.containsKey("Ada"));      // true
System.out.println(ages.containsKey("Bo"));       // false
System.out.println(ages.getOrDefault("Bo", 0));   // 0 — fallback

Prefer containsKey or getOrDefault over a raw get when a key might be absent.


▶ Try it: run this — see the difference between a present and a missing key.



get(key) on a key that is not in the map returns...


getOrDefault("Bo", 0) when "Bo" is missing returns...


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("a", 5);
    System.out.println(m.containsKey("a"));
    System.out.println(m.getOrDefault("b", 0));
}}

To check whether a key exists without risking null, use...


True or false?