Pages

Thursday, August 25, 2011

Type Safe Collection Conversion

I was reading a great article by a friend of mine Checking an Unchecked Cast in Java 5 or Later where he refers to some of the rules from Josh Bloch about making type safe conversions. It was interesting. Glen also provides a good code example of how he does a type safe conversion. I thought I would provide a couple of examples using a List converter. I have heard that a number of folks do not like returning <T> from a method which has a collection associated with it. However like any tool, it is up to the person using it not to hurt themselves (i.e. a screwdriver is not a hammer). In this example I have a couple of methods which do type safe conversion of a List of something. We need to know in advance what we expect that something to be. This is just one example of how you can do a conversion on a collection. I would like to note that there are methods on the Collections class which returns a checked collection. This ensures that any object added to a collection is of particular type. As the API notes, this is for the addition of classes after the collection has been turned into a checked collection. It does not check the Collection for previously added objects. The code below checks all of the object types before doing the conversion, and fails if it encounters the wrong type.

4 comments :