Enum Map

The EnumMap class provides a Map implementation whose keys are the members of the same enum. Null keys are not permitted; any attempt to store a null key results in a thrown NullPointerException. Because an enum map is represented internally as an array, an enum map approaches an array in terms of performance.

EnumMap supplies the following constructors:

■ EnumMap(Class<K> keyType) creates an empty enum map with the specified keyType. This constructor throws NullPointerException when keyType contains the null reference.

■ EnumMap(EnumMap<K,? extends V> map) creates an enum map with the same key type as map, and with map's entries. This constructor throws NullPointerException when map contains the null reference.

■ EnumMap(Map<K,? extends V> map) creates an enum map initialized with map's entries. If map is an EnumMap instance, this constructor behaves like the previous constructor. Otherwise, map must contain at least one entry in order to determine the new enum map's key type. This constructor throws NullPointerException when map contains the null reference, and IllegalArgumentException when map is not an EnumMap instance and is empty.

Listing 8-28 demonstrates EnumMap.

Listing 8-28. An enum map of Coin constants import java.util.EnumMap; import java.util.Map;

enum Coin {

PENNY, NICKEL, DIME, OUARTER

public class EnumMapDemo {

public static void main(String[] args) {

Map<Coin, Integer> map = new EnumMap<Coin, Integer>(Coin.class);

map.put(Coin.NICKEL, 5);

map.put(Coin.OUARTER, 25);

System.out.println(map);

Map<Coin,Integer> mapCopy = new EnumMap<Coin, Integer>(map); System.out.println(mapCopy);

When you run this application, it generates the following output:

{PENNY=1, NICKEL=5, DIME=10, OUARTER=25} {PENNY=1, NICKEL=5, DIME=10, OUARTER=25}

Was this article helpful?

0 -1

Post a comment