O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required