Java中for迴圈的6種寫法

來源:互聯網
上載者:User

標籤:


List<String> list = new ArrayList<String>();

/**
* 方法一:最普通的不加思考的寫法
* <p>
* 優點:較常見,易於理解
* <p>
* 缺點:每次都要計算list.size()
*/
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
/**
* 方法二:數組長度提取出來
* <p>
* 優點:不必每次都計算
* <p>
* 缺點:1、m的範圍不夠小,違反了最小範圍原則 2、不能在for迴圈中操作list的大小,比如除去或新加一個元素
*/
int m = list.size();
for (int i = 0; i < m; i++) {
System.out.println(list.get(i));
}
/**
* 方法三:數組長度提取出來
* <p>
* 優點:1、不必每次都計算 2、所有變數的範圍都遵循了最小範圍原則
* <p>
* 缺點:1、m的範圍不夠小,違反了最小範圍原則 2、不能在for迴圈中操作list的大小,比如除去或新加一個元素
*/
for (int i = 0, n = list.size(); i < n; i++) {
System.out.println(list.get(i));
}
/**
* 方法四:採用倒序的寫法
* <p>
* 優點:1、不必每次都計算 2、所有變數的範圍都遵循了最小範圍原則
* <p>
* 缺點:1、結果的順序會反 2、看起來不習慣,不易讀懂
* <p>
* 適用場合:與顯示結果順序無關的地方:比如儲存之前資料的校正
*/
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}
/**
* 方法五:Iterator遍曆
* <p>
* 優點:簡潔
* <p>
* 缺點:
*/
for (Iterator<String> it = list.iterator(); it.hasNext();) {
System.out.println(it.next());
}
/**
* 方法六:jdk1.5新寫法
* <p>
* 優點:簡潔結合泛型使用更簡潔
* <p>
* 缺點:jdk1.4向下不相容
*/
for (Object o : list) {
System.out.println(o);
}

 

Java中for迴圈的6種寫法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.