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());
}
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development