Features new to Java: documenting my discovery as it happens
I'm a fan of Perl and its expressiveness but at work I write Java which I find to be rather verbose with lots of boilerplate. I'm finally at the stage where I'm designing a new project from scratch and I'm free to break away from Java 1.3 and 1.4 compatibility and start taking advantage of the Java 5 & 6 features.
Generics -- In the past I've been used to doing the following...
List things = new LinkedList();
things.add(new Thing("thing1"));
things.add(new Thing("thing2"));...and then later...
Iterator it = things.iterator();
while(it.hasNext()){
Thing a = (Thing)it.next();
log.debug("here's a thing: "+a);
}...see the list just holds the lowest common denominator: Object,
so we have to cast back from Object
to Thing. That's fine but really the compiler can't stop you incorrectly casting it to something else, e.g. AnotherThing, which can happen if the two sections of code are written at different times, perhaps by different authors and one author has moved on a bit. And you want code that will do something with "AnyThing"
not just treat it like a "Thing"?
Well, chances are you'll have a base class of Thing
to work from but then you'll have to do your own introspection to
find out which class of "Thing" you're dealing with and then you'll have to have wrapper classes -- that's kinda ugly. Stepping out of Java and into the real world for the moment, templates have been in C++, like, forever! Now Java has generics which allows us to define our list as holding a particular type...
List <Thing> things = new LinkedList(<Thing>);
...then the compiler knows what goes in the List
and can tell you if you try and use it wrongly. You don't have to
cast back out again.
Enhanced for -- "foreach" comes to Java!
I have a list of string arrays and I'm going to do something with
each one; I would previously do this to debug out a List
of String
arrays...
Iterator
it = somelist.iterator();
while
(it.hasNext()) {
String[]
a = (String[])it.next();
log.debug("assocs
is "+Arrays.asList(a));
}
...but since the List
is Iterable,
I can now do this...
for
(String[] a : assocs){
log.debug("assocs
is "+Arrays.asList(a));
}
This would work with an array too. It's tighter and more to the
point: more expressive.
Annotations â I've been seeing the annotations as I debug
into the JDK classes (I have the JDK sources mounted in Eclipse) but
until I started looking at JUnit 4.0 I haven't been that interested
in what they can do for me.