IMPERIUM Generics Can Look Scary

Tiger Adds Generics

It's well-known in the Java world that J2SE 5.0 - codenamed Tiger - added, amongst other things, Generics, or if you prefer, Parameterized Types

Generics have been added in order to improve compiler checked type safety. While they have a major impact in the area of Container Types, they appear in many other places, including the parameterization of Class itself.

In many cases, the use of an API is simpler than its declaration, as you will see.


A Simple Code Example

Let's look at a fairly innocent piece of code from the pre-Generics world, then transform it to use parameterized types.


			Collection c = new ArrayList();

			c.add("fred");
			c.add("harry");
			c.add("alex");

			String maxi = (String)Collections.max(c);

             

Which may not look too different from this generified fragment:

			Collection<String> c = new ArrayList<String>();

			c.add("fred");
			c.add("harry");
			c.add("alex");

			String maxi = Collections.max(c);

            

You might be forgiven for thinking that all we've done here is add in the <String> Type Parameter, and lost the explicit cast to String when retrieving the maximum from the Collection. In fact, we now have compile time checking that we are using our collections safely.


Now Let's Look at the API

Up to J2SE 1.4, the signature of the Collections.max method was as follows:

             public static Object max(Collection coll)
             

BUT from Tiger onwards, we have the rather scary

             public static <T extends Object & Comparable<? super T>>
                            T max(Collection<? extends T> coll)
             


Just Keep Calm

OK. Some examples of Generified Java look scary, but by learning the basics, and keeping calm, your current Java knowledge will see you through.


Want To Learn More?
We run One Day Crash Courses in a variety of topics, including Generics and other Java 5 New Features

Copyright © 2005 Imperium Computing Consultants Ltd. All rights reserved