java: 增強for 迴圈(enhanced for loop)

來源:互聯網
上載者:User

增強for 迴圈(enhanced for loop)
所謂“增強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 ?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.