Java Reference
In-Depth Information
Note the formatting used in the above examples:
There are no spaces within the angle brackets ( < and > ).
There is no space between the collection name and the angle brackets.
There is no space between the angle brackets and the curved brackets (when calling a
constructor).
These are the coding conventions used in the JSRs and in several Sun documents describ-
ing the new features of JDK 5; however, currently there are no formal conventions.
Enhanced for Loop
In our example of generics, we used an Iterator to step through the items in the collection.
To reiterate, our code example looked like this:
for (Iterator<Dog> i = c.iterator(); i.hasNext(); ) {
String name = i.next().getName();
However, this is overly wordy: in most cases you will want to step through all the items in
your iterator one by one. So why spell it out for the compiler in this way?
JDK 5 has made the use of iterators in for loops much easier. Consider the following con-
struct, which does the same work:
for (Dog mutt : c) {
String name = mutt.getName();
It may help to read the colon ( : ) as “in.” Thus, the statement for (Dog mutt : c) would
read “for each mutt in collection c.”
Note Many people are curious about why Sun chose to use the colon instead of using the words “in” or
“foreach.” Quite simply, Sun wanted to avoid introducing any new keywords, which might potentially break
existing source code. All your existing code should compile and run without any problems under JDK 5.
The enhanced for loop can also work with standard arrays. The following code gives an
example of iterating over an array of Strings without using the enhanced for loop:
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
Search WWH ::




Custom Search