Java Reference
In-Depth Information
•
EnumMap(Map<K,? extends V> m)
creates an enum map initialized
with
m
'sentries.If
m
isan
EnumMap
instance,thisconstructorbehaveslikethe
previousconstructor.Otherwise,
m
mustcontainatleastoneentryinordertode-
terminethenewenummap'skeytype.Thisconstructorthrows
NullPoint-
erException
when
m
contains the null reference, and
IllegalArgu-
mentException
when
m
is not an
EnumMap
instance and is empty.
Listing 5-23.
An enum map of
Coin
constants
import java.util.EnumMap;
import java.util.Map;
enum Coin
{
PENNY, NICKEL, DIME, QUARTER
}
class EnumMapDemo
{
public static void main(String[] args)
{
Map<Coin, Integer> map = new EnumMap<>(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<>(map);
System.out.println(mapCopy);
}
}
When you run this application, it generates the following output:
{PENNY=1, NICKEL=5, DIME=10, QUARTER=25}
{PENNY=1, NICKEL=5, DIME=10, QUARTER=25}