5.13. Creating Typed Collections and Maps
Problem
You need to guarantee that
a Collection or
a Map only contains objects of a certain type.
Solution
Use TypedCollection.decorate()
to create a Collection
that only accepts objects of a specified type. Supply an existing
Collection along with the Class
that all elements should be constrained to.
TypedCollection will decorate this existing
Collection, validating elements as they are added
to a Collection. The following example creates a
Collection that will only accept strings:
List existingList = new ArrayList( ); Collection typedCollection = TypedCollection.decorate( existingList, String.class ); // This will add a String typedCollection.add( "STRING" ); // And, This will throw an IllegalArgumentException typedCollection.add( new Long(28) );
Similarly, if you want to constrain keys and values to specified
types, pass a Map to TypedMap.decorate( )
method, specifying a Class for both the
key and the value. In the following example,
typedMap only accepts String
keys and Number values:
Map existingMap = new HashMap( ); Map typedMap = TypedMap.decorate( existingMap, String.class, Number.class ); // This will add a String key and a Double value typedMap.put( "TEST", new Double( 3.40 ) ); // Both of these throw an IllegalArgumentException typedMap.put( new Long(202), new Double( 3.40 ) ); typedMap.put( "BLAH", "BLAH" );
TypedCollection and TypedMap
will decorate any existing Collection or
Map and will throw an
IllegalArgumentException if ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access