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 ...

Get Jakarta Commons Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.