LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Find the Error · Question 8

Error: changing an entry's key Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links