Item 1: The
Unless you are forced to use native types because of their support for arithmetic operations, it is preferable to use subclasses of
An exception to this rule is when the iteration is around an array of a native numeric type.
Item 4: Watch out for null pointers.
Item 7. Do not modify the list during iteration.
Item 8. Consider returning an
This effectively hides the details of the current implementation and allows for later optimizations such as lazy construction of each iterated item
Item 9. Consider returning
Item 10. Consider lazy construction of iterated items.
could produce the following optimized translation of the first example.
Read full article from Nuances of the Java 5.0 for-each Loop | Java.net
for
-each
loop allows only one iteration variable, which precludes simultaneously iterating over two or more arrays or collections.
Essentially, an intermediate
Iterator
of the right kind is created.public Integer sum (List<Integer> liszt) {
int total=0;
for(Iterator<Integer> iter=liszt.iterator(); iter.hasNext();) {
int num = ((Integer)iter.next()).intValue();
total += num;
}
return new Integer(total);
}
Item 3: Beware of auto-unboxing.Unless you are forced to use native types because of their support for arithmetic operations, it is preferable to use subclasses of
Number
(Integer
, Double
, etc.) in loop variables rather than the equivalent native types (int
,double
, etc.).An exception to this rule is when the iteration is around an array of a native numeric type.
Item 4: Watch out for null pointers.
if (null != liszt) for(int num : liszt)
Item 6. Return zero length arrays or empty lists rather than nullsItem 7. Do not modify the list during iteration.
Item 8. Consider returning an
Iterable
rather than a List
.This effectively hides the details of the current implementation and allows for later optimizations such as lazy construction of each iterated item
Item 9. Consider returning
Iterable
views rather than implementing Iterable
.Item 10. Consider lazy construction of iterated items.
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
try {return !results.isAfterLast();}
catch (SQLException e) {return false;}
}
public T next() {
try {
results.next();
return rowFactory.create(results);
}catch (SQLException e) {e.printStackTrace();return null;}
}
public void remove() {
throw new UnsupportedOperationException();
}
that List
should implement java.util.RandomAccess
. This is just a marker interface--it declares no methods--and is meant to provide a means for generic methods to optimize their for
loops involving List
s if the List
implementation's random access mechanisms are faster than iteration. For example, in the Java Collections framework, the ArrayList
, Stack
, and Vector
implement RandomAccess
. A compilercould produce the following optimized translation of the first example.
Read full article from Nuances of the Java 5.0 for-each Loop | Java.net
No comments:
Post a Comment