Mega Code Archive

 
Categories / Java Book / 005 Collection
 

0310 The EnumMap Class

EnumMap extends AbstractMap and implements Map. It uses an enum type as keys. The EnumMap class provides a Map implementation whose keys are the members of the same enum. Null keys are not permitted. It is a generic class that has this declaration: class EnumMap<K extends Enum<K>, V> K specifies the type of key V specifies the type of value. K must extend Enum<K>, which enforces that hat the keys must be of an enum type. EnumMap defines the following constructors: EnumMap(Class<K> kType) creates an empty EnumMap of type kType. EnumMap(Map<K, ? extends V> m) creates an EnumMap map that contains the same entries as m. EnumMap(EnumMap<K, ? extends V> em) creates an EnumMap initialized with the values in em. The following code stores Size enum to a EnumMap. import java.util.EnumMap; public class Main { public static void main(String[] args) { EnumMap<Size, String> sizeMap = new EnumMap<Size, String>(Size.class); sizeMap.put(Size.S, "S"); sizeMap.put(Size.M, "M"); sizeMap.put(Size.L, "L"); sizeMap.put(Size.XL, "XL"); sizeMap.put(Size.XXL, "XXL"); sizeMap.put(Size.XXXL, "XXXL"); for (Size size : Size.values()) { System.out.println(size + ":" + sizeMap.get(size)); } } } enum Size { S, M, L, XL, XXL, XXXL; } The following code maps enum to an integer. import java.util.EnumMap; import java.util.Map; enum Coin { PENNY, NICKEL, DIME, QUARTER } public class Main { public static void main(String[] args) { Map<Coin, Integer> map = new EnumMap<Coin, Integer>(Coin.class); map.put(Coin.PENNY, 1); map.put(Coin.NICKEL, 5); map.put(Coin.DIME, 10); map.put(Coin.QUARTER, 25); System.out.println(map); Map<Coin, Integer> mapCopy = new EnumMap<Coin, Integer>(map); System.out.println(mapCopy); } }