Compilation in J2SE 5.0
One of my aims is to make the examples portable, which means that they should compile and execute in J2SE 5.0 and J2SE 1.4. At the moment, May 2005, many Java users haven't upgraded to the latest version, and many PCs come with JRE 1.4 preinstalled.
As mentioned in the Preface, the main areas where I lose out because of this portability are in type-safe collections and the nanosecond time method, System.nanoTime(). The Java 3D nanosecond timer is a good replacement for nanoTime(). But what about type-safe collections?
What Is a Type-Safe Collection?
A type-safe collection is a generified collection declared with a type argument for its generic component. For example, this J2SE 1.4 code doesn't use generics:
ArrayList al = new ArrayList();
al.add(0, new Integer(42));
int num = ((Integer) al.get(0)).intValue();Collections without generic arguments are called raw types.
The following J2SE 5.0 code uses a generified ArrayList with an Integer type:
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0, new Integer(42));
int num = ((Integer) al.get(0)).intValue();Type safety means that the compiler can detect if the programmer tries to add a non-Integer object to the ArrayList. Poor coding like that would only be caught at runtime in J2SE 1.4, as a ClassCastException.
Generified collections can make use of J2SE 5.0's enhanced for loop, enumerations, and autoboxing. For example, the code snippet above can be revised to employ autoboxing and autounboxing:
ArrayList<Integer> ...