LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Find the Error · Question 4

Error: calling firstKey through a Map reference Answer, explanation & discussion

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

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

Main.java
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> ranks = new TreeMap<>();
        ranks.put(2, "silver"); ranks.put(1, "gold");
        System.out.println(ranks.firstKey());
    }
}
  • A TreeMap cannot hold Integers
  • B firstKey belongs to SortedMap/TreeMap, not Map; declare the variable as TreeMap or SortedMap to use it Correct
  • C put must come after firstKey
  • D firstKey needs an argument
Correct Answer: Option B

The compiler only knows the methods of the declared type, Map.

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