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);
m.put("a", 2);
System.out.println(m.get("a") + " " + m.size());
}
}2 1
- Expecting
1 1: unlikeaddin aHashSet,putwith an existing key does not keep the old entry, it replaces the value; it even returns the old value,1. - Expecting a size of 2: a map holds each key once, and
sizecounts keys, so twoputcalls with one key leave one pair.
- What does the second
putreturn here? - How do you add a pair only if the key is not in the map yet?