What will be displayed with the following code?

import java.util.EnumMap;
import java.util.Map;

enum Types { A, B, C }

public class Test {
    static Integer value;
    public static void main(String args[]) {
        Map<Types, Integer> m = new EnumMap<Types, Integer>(Types.class);
 m.put(Types.A, value);
        System.out.println(m);
    }
}
Explanation
The collection EnumMap has a parameterized constructor that specifies the key enum type.
This type is stored in an instance of the collection, and used to control the value of the key during the program:

enum Types { A, B, C }
enum Wrong { A }
public class Test {
    public static void main(String... args) {
        Map<Types, Integer> m = new EnumMap<Types, Integer>(Types.class);
        Map m1 = m; // 
        m1.put(Wrong.A, null); // error 
ClassCastException
    }
}

If you use more popular implementation of java.util.Map (eg., HashMap, TreeMap), then the same code will be executed without errors:
 
Map<Types, Integer> m = new HashMap<Types, Integer>();
Map m1 = m;
m1.put(Wrong.A, null); // wrong key, but no error
 

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести