Question 8
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<>(Map.of("old", 1));
for (Map.Entry<String, Integer> e : m.entrySet()) {
e.setKey("new");
}
System.out.println(m);
}
}
- A entrySet cannot be looped
- B Map.Entry has setValue but no setKey – keys cannot be changed in place; remove the old key and put the new one Correct
- C e must be final
- D HashMap entries are immutable entirely
Correct Answer: Option B
Changing a key in place would break the hashing structure.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!