THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

21.9.2. EnumMap


The EnumMap<KextendsEnum,V> is a special map that uses enum values as keys. All values in the
map must come from the same enum type. Just like EnumSet the enum values are ordered by their natural
order, and the iterator is weakly consistent.


Suppose you were writing an application that dynamically builds and displays an on-line form, based on a
description written in a structured format such as XML. Given the set of expected form elements as an enum


enum FormElements { NAME, STREET, CITY, ZIP }


you could create an enum map to represent a filled in form, where the keys are the form elements and the
values are whatever the user entered.


EnumMap has three constructors:


publicEnumMap(Class<K> keyType)

Creates an empty EnumMap that can hold keys of the given enum type.

publicEnumMap(EnumMap<K,? extends V> map)

Creates an EnumMap of the same enum type as map and containing all the
elements of map.

publicEnumMap(Map<K,? extends V> map)

Creates an EnumMap from the given map. If the map is an EnumMap, a copy
is returned. Any other map must contain one or more keys, all of which are
constants from the same enum; this enum will be the enum type of the
returned EnumMap. If map is empty and is not an EnumMap then
IllegalArgumentException is thrown because there is no specified
enum type for this map.

EnumMap is implemented using arrays internally, so it is compact and efficient.


21.10. Wrapped Collections and the Collections Class


The Collections class defines a range of static utility methods that operate on collections. The utility
methods can be broadly classified into two groups: those that provide wrapped collections and those that
don't. The wrapped collections allow you to present a different view of an underlying collection. There are
three different views: a read-only view, a type-safe view, and a synchronized view. The first two are discussed
in this section, synchronized wrappers are discussed later with the concurrent collections. First we discuss the
general utility methods.


21.10.1. The Collections Utilities


The Collections class defines many useful utility methods. You can find the minimum and maximum
valued elements in a collection:

Free download pdf