Topics Index

Add Numbers to EnumMap

If you need explanation Read this topic

If you need Answer Take test on this topic

Add Numbers to EnumMap
What will be the output of the following program?
import java.util.*;
public class AddNumbers {
    enum NUMBERS {
        One, Two, Three, Four, Five;
    public static void main(String[] args) {
        EnumMap<NUMBERS, String> em = new EnumMap<NUMBERS, String>(NUMBERS.class);
        em.put(NUMBERS.Two, "2");
        em.put(NUMBERS.Three, "3");
        em.put(NUMBERS.One, "1");
        em.put(NUMBERS.Four, "4");

A. {One=1, Two=2, Three=3, Four=4}
B. {Two=2, Three=3, One=1, Four=4}
C. Some other output
D. Compilation Error or Runtime Error
Topic: Java EnumMap

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 A.

An enum type is a special data type that enables
for a variable to be a set of predefined constants.
The variable must be equal to one of the values
that have been predefined for it.

In that program enum method will print constant one by one because of EnumMap methods...

Posted by Shubham Bansal    2014-10-20 13:21:13

Ans is A...In Java enum is special data type which contains Constants and Methods,Constructors etc...Enum is list of Constants,by default enum extends Enum class so that enum cant extend any other class Bcz Java does not support multiple inheritance

EnumMap is an Special map which uses keys as Enum constants of Single type and  keys must unique and nul insertions is not possible in the Keys.

enumMap maintains the order of keys(maintains same order in EnumMap similar to Constants declared in enum)
coming to example we are creating an enumMap with NUMBERS and String..
so that keys of type Enum NUMBERS and Values are Strings

clear()---> wil remove the all mappings from this Map
here we are inserting

Next we are printing the em it wil print

one,two,three,four Bcz it wil consider the order of enum

Posted by Uday Kumar    2014-10-20 14:43:16

ans a..
enumMap extends AbstractMap for use with enum keys.
AbstractMap is a superclass for all concrete map implementation.
and also it implements map.

it is specifically for use with keys of an enum type.

class EnumMap<K extends enum<K>,V>

here K specifies type of key,V specifies type of value.

in this program K is NUMBER which extends enum NUMBER, value type is String.

by using put() values and key stored in enumMap in order of key value.
thn sop get printd

Posted by Maheshwari Natarajan    2014-10-20 15:54:18

This dose is now closed and the winners are Shubham Bansal,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Shashanka Mogaliraju. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2014-10-21 04:24:25

© meritcampus 2019

All Rights Reserved.

Open In App