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