Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Program66
{
    public static void main(String[] args)
    {
        Map<String, Integer> scores = new TreeMap<String, Integer>();
        scores.put("b", 2); scores.put("a", 1); scores.put("c", 3);
        System.out.println(
            ((TreeMap<String, Integer>) scores).firstKey() + " " + scores);
    }
}

  • A.b {b=2, a=1, c=3}
  • B.a {a=1, b=2, c=3}
  • C.a {b=2, a=1, c=3}
  • D.c {c=3, b=2, a=1}

Answer: B

A TreeMap keeps its keys in natural order regardless of insertion order, so firstKey is a and the map prints sorted. The cast is needed only because firstKey belongs to SortedMap rather than to the Map interface the variable is declared with.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.