Introduction


JDK 1.5 introduced two new concepts, Generics and AutoBoxing/Unboxing, and two new language features, "foreach" and typesafe enumerations; these features are covered in this chapter.

Generics allow a class to be tailored for a variety of argument/return types at compile time. It provides similar functionality to the Templates mechanism that has been in C++ for some years. When used with the Collections classes (see Chapter 7), Generics significantly increase type safety and remove the requirement for downcasting every object that is retrieved from a Collection (either directly or via an Iterator).

Recipe 5.3 discussed the "Wrapper" classes; these classes provide Objects that represent primitive values. Autoboxing automates the conversion from primitive to Object and vice versa.

The new " foreach" mechanism does not give Java a new keyword; the "for" keyword is still used. However, the syntax is changed slightly to resemble the "for value in list" construct in languages such as the Unix Bourne Shell and the Awk scripting language. This makes it much easier to use Collections, often eliminating the need to obtain an Iterator.

Finally, the Typesafe Enumerations feature provides a mechanism for dealing with a small list of discrete values, such as months, colors, and the like. It combines the enum syntax from Java's predecessor, C, with the Typesafe Enumeration design pattern, giving JDK 1.5 the best of both worlds.

These represent, for the most part, changes to the compiler and the class libraries, rather than changes to the underlying Java Virtual Machine; the changes were implemented by having the compiler map from new constructions to calls on classes, rather than by perturbing the JVM. Because of this, in order to maintain backward compatibility (so that the 1.5 compiler can compile 1.4-level code), these new mechanisms are not enabled by default. So get very used to typing the magical incantation:

javac -source 1.5  file .java 

For without this, the examples in this chapter will universally fail to compile. You have been warned!

You do not, at least, need any special options to the java command that invokes the JVM to interpret your class file because, as mentioned, the changes are in the compiler, not in the JVM itself. This does not mean that most of this chapter's material can be compiled on 1.5 and run on 1.4; because of the need for extra methods in the Java runtime, you can't run most of the generated code under 1.4.

See Also

The compiler techniques used in compiling these new constructs in a backward-compatible way include erasure and bridging, topics discussed in an article by O'Reilly author William Grosso, which can be read online at http://today.java.net/pub/a/today/2003/12/02/explorations.html.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net