Datasheet
The specific type of exception is specified when an instance of the Executor class is created inside main.
The
execute method throws an arbitrary exception that it is unaware of until a concrete instance of the
Executor interface is created.
Enhanced for Loop
The for loop has been modified to provide a cleaner way to process an iterator. Using a for loop with
an iterator is error prone because of the slight mangling of the usual form of the
for loop since the
update clause is placed in the body of the loop. Some languages have a foreach keyword that cleans
up the syntax for processing iterators. Java opted not to introduce a new keyword, instead deciding to
keep it simple and introduce a new use of the colon. Traditionally, a developer will write the following
code to use an iterator:
for(Iterator iter = intArray.iterator(); iter.hasNext(); ) {
Integer intObject = (Integer)iter.next();
// ... more statements to use intObject ...
}
The problem inherent in this code lies in the missing update clause of the for loop. The code that
advances the iterator is moved into the body of the
for loop out of necessity, because it also returns the
next object. The new and improved syntax that does the same thing as the previous code snippet is as
follows:
for(Integer intObject : intArray) {
// ... same statements as above go here ...
}
This code is much cleaner and easier to read. It eliminates all the potential from the previous construct to
introduce errors into the program. If this is coupled with a generic collection, the type of the object is
checked versus the type inside the collection at compile time.
Support for this new
for loop requires a change only to the compiler. The code generated is no different
from the same code written in the traditional way. The compiler might translate the previous code into
the following, for example:
for(Iterator<Integer> $iter = intArray.iterator(); $iter.hasNext(); ) {
Integer intObject = $iter.next();
// ... statements ...
}
The use of the dollar sign in the identifier in this example merely means the compiler generates a unique
identifier for the expansion of the new
for loop syntax into the more traditional form before compiling.
The same syntax for using an iterator on a collection works for an array. Using the new
for loop syntax
on an array is the same as using it on a collection:
for(String strObject : stringArray) {
// ... statements here using strObject ...
}
16
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 16