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

Discussion

What will be the output of the program?

import java.util.*;

public class Snippet50
{
    public static void main(String[] args)
    {
        Map<Character, List<String>> index =
            new HashMap<Character, List<String>>();
        for (String w : new String[] {"ant", "ape", "bee"})
        {
            char k = w.charAt(0);
            if (!index.containsKey(k)) index.put(
                k, new ArrayList<String>());
            index.get(k).add(w);
        }
        System.out.println(index.get('a').size() + " " + index.size());
    }
}

  • A.The program prints 3 2
  • B.The program prints 2 2
  • C.The program prints 2 3
  • D.The program prints 3 3

Answer: B

This is the grouping idiom: containsKey decides whether a bucket exists, and get returns the SAME list each time so the appends accumulate. Two words start with a, giving a list of 2, and there are two distinct first letters, so the map holds 2 entries. get returns the stored reference, not a copy.

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

Post your comment

Please log in or register to post a comment.