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
Войдите чтобы поставить Нравится
Войдите чтобы прокомментировать