所谓“增强的for 循环”,主要也是针对容器的。使用该项特性时,开发者可以将“利用iterator
遍历容器”的逻辑交给编译器来处理。例如下列代码:
void cancelAll(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask tt = (TimerTask) i.next();
tt.cancel();
}
}
可以用增强的for 循环改写为:
void cancelAll(Collection c) {
for (Object o : c)
((TimerTask)o).close();
}
编译器判断对象c 是一个Collection 子对象(即是容器)之后,就会允许使用增强的for 循环
形式,并自动取到c 的迭代器,自动遍历c 中的每个元素。
可以看到,上面的代码中仍然有一个强制类型转换(((TimerTask)o).close();)。实际上,这
项特性应该普遍地与泛型结合,以获得最大的利益。结合泛型之后,上述代码变成:
void cancelAll(Collection c) {
for (TimerTask task : c)
task.cancel();
}
public enum LogLevel {
VERBOSE(2, "verbose", 'V'), //$NON-NLS-1$
DEBUG(3, "debug", 'D'), //$NON-NLS-1$
INFO(4, "info", 'I'), //$NON-NLS-1$
WARN(5, "warn", 'W'), //$NON-NLS-1$
ERROR(6, "error", 'E'), //$NON-NLS-1$
ASSERT(7, "assert", 'A'); //$NON-NLS-1$
private int mPriorityLevel;
private String mStringValue;
private char mPriorityLetter;
LogLevel(int intPriority, String stringValue, char priorityChar) {
mPriorityLevel = intPriority;
mStringValue = stringValue;
mPriorityLetter = priorityChar;
}
/**
* Circular buffer containing the logcat output. This is unfiltered.
* The valid content goes from <code>mBufferStart</code> to
* <code>mBufferEnd - 1</code>. Therefore its number of item is
* <code>mBufferEnd - mBufferStart</code>.
*/
private LogMessage mKernerMsg = new LogMessage();
/*
* this below inherited from log.java
*/
/**
* Returns the {@link LogLevel} enum matching the specified letter.
* @param letter the letter matching a <code>LogLevel</code> enum
* @return a <code>LogLevel</code> object or <code>null</code> if no match were found.
*/
public static LogLevel getByLetter(char letter) {
for (LogLevel mode : values()) {
if (mode.mPriorityLetter == letter) {
return mode;
}
}
return null;
}
怎么理解这个values ?