Menu
Topics Index
...
`

Collections Map


If you need explanation Read this topic

If you need Answer Take test on this topic

Collections Map
What will be the output of the following program?
import java.util.*;

public class Wonder {
    private enum Gender {
        M, F
    }
    public static void main(String[] args) {
        printSize(new HashMap<Gender, Gender>());
        printSize(new EnumMap<Gender, Gender>(Gender.class));
    }
    private static void printSize(Map<Gender, Gender> map) {
        map.put(Gender.M, Gender.F);
        map.put(Gender.F, Gender.M);
        map.put(Gender.M, Gender.M);
        map.put(Gender.F, Gender.F);
        Set<Map.Entry<Gender, Gender>> set = new HashSet<Map.Entry<Gender, Gender>>(map.entrySet());
        for (Map.Entry<Gender, Gender> e : map.entrySet())
            set.add(new AbstractMap.SimpleEntry<Gender, Gender>(e.getKey(), e.getValue()));
        System.out.print(set.size());
    }
}

A. 12
B. 21
C. 22
D. Some other output
E. Compilation Error or Runtime error
Topic: Collection Framework In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is C. For the first call of printSize though there are four put calls but already existing keys and corresponding values are being added. So only two distinct elements are added to the map and from the map to the set. so for both the calls the size of the set will be 2.

Posted by Nikhil Sulibhavi    2014-05-19 12:57:52


Answer : C
> Both the printSize()  call return 2 as both the times only 2 distinct elements are being added

Posted by Deepak Kumar Yadav    2014-05-19 13:12:03


Congratulations Nikhil Sulibhavi. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-05-20 04:32:53


© meritcampus 2019

All Rights Reserved.

Open In App