Search |
||
Eye of the Tiger - Generics in J2SE 1.5Posted by sam_dalton on December 3, 2003 at 4:04 AM PST
Once again (actually it seems like an age since the last one), a new incarnation of the J2SE is nearing release. This time there seems to be a lot of completely new language features (that is not to say that previous releases have been insignificant). Below is a list of major features:
As you can see these are a fair number of totally new (to Java anyway) features, but what do they all mean? Well starting at the top, here is a brief description of Generics:
static void dumpSam(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
String s = (String) i.next();
if (s.indexOf("sam") > 0)
System.out.println(s);
}
}
The above code dumps the items of a collection that contain the word "sam" to the screen using 1.4 syntax. Nothing much wrong with it, except that the cast is ugly, and there is the potential of a ClassCastException at runtime. Now if we look at how this might be done usign generics, we see that is is much prettier, and also guaranteed not to fail at runtime:
static void dumpSam(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); ) {
String s = i.next();
if (s.indexOf("sam") > 0)
System.out.println(s);
}
}
We can see from the signature of the method ( Now this may all look a little alien to start with, but I am sure once we get used to seeing generics it will actually be far clearer than code written with casts. What's more, you can try out generics now by downloading the prototype implementation of the spec. I will blog about some of the other new Java 1.5 features at a later date (once I have had a chance to play with them.) »
Related Topics >>
J2SE Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|