Java Reference
In-Depth Information
System . out . println ( s );
}
// Show the Java 5 foreach loop - do not modernize to Java 8
List < String > list = Arrays . asList ( data );
for
for ( String s : list ) {
System . out . println ( s );
}
In modern Java, the foreach loop is used more commonly than the prior for loop. The main
times when the older style would be used are:
▪ When you need the number of each element for calculation or indexing a target array or
arrays
▪ When you are creating new data using a numeric index
▪ When the control involves floating point calculations rather than integer
▪ When you want to remove items from the collection during iteration, so you need expli-
cit access to the iterator
Java 5 enums
Enumerations implement the Typesafe Enumeration Pattern described in Josh Bloch's book
Effective Java . Bloch worked at Sun to implement this language feature, among others. The
basic idea is that where you have a small, rarely changing set of values, it makes sense to list
them and have them known at compile time. For example, the colors at a stoplight are red,
amber, and green; we might code this as in Example A-2 , at a bare minimum.
Example A-2. Color.java
public enum Color {
RED, AMBER, GREEN
}
Enums are covered in Using Typesafe Enumerations .
Java 5 annotations
Java Annotations are metadata-like “sticky notes” that you can attach to various places in
your Java code to provide extra information beyond normal Java syntax and semantics. Some
(such as java.lang.Override ) are only used at compile time; others—the majority—are
consulted at runtime. They are described, with examples, in Using and Defining Annotations .
Search WWH ::




Custom Search