Back to questions
JuniorTheoryCommon
What does the program print?
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
System.out.println(m.get("z") + " " + m.size());
}
}null 1
- Expecting
0: a missing key givesnull, not the zero ofint; callgetOrDefault("z", 0)when you need a number. - Expecting an exception:
getreturnsnullfor a missing key; the exception comes only when thatnullis unboxed, as inint n = m.get("z");.
- How can you tell a missing key from a key stored with the value
null? - What does
m.getOrDefault("z", 0)return here?