Java中普通for循環(huán)和增強for循環(huán)的一些區(qū)別

Java中for的幾種常見形式

  1. For loop using index.
for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    body-of-loop
}
  1. Loop using explicit iterator.
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    body-of-loop
}
  1. Foreach loop over all elements in arr.
for (type var : coll) {
    body-of-loop
}

For循環(huán)用來處理哪些數(shù)據(jù)結(jié)構(gòu)

  1. 數(shù)組
int[] a = {1,2,3,4,5,6};
int[] b = new int[]{1,2,3,4,5,6};
int[] c = new int[6];
for (int i = 0; i < a.length; i++) {
    System.out.println(i);
}
for (int i : a) {
    System.out.println(i);
}
  1. 實現(xiàn)了java.util.Iterator的類
````aidl
import java.util.Iterator;

/**
 * Created by MoXingwang on 2017/6/30.
 */
public class IterableTest<E> implements Iterable<E> {

    public static void main(String[] args) {
        IterableTest<Integer> integers = new IterableTest<Integer>();
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator() {

            @Override
            public boolean hasNext() {
                //...
                return false;
            }

            @Override
            public Object next() {
                //...
                return null;
            }

            @Override
            public void remove() {
                //...
            }
        };
    }
}

普通for遍歷和增強for的一些區(qū)別

增強的for循環(huán)的底層使用迭代器來實現(xiàn),所以它就與普通for循環(huán)有一些差異

  1. 增強for使用增強for循環(huán)的時候不能使用集合刪除集合中的元素;
  2. 增強for循環(huán)不能使用迭代器中的方法,例如remove()方法刪除元素;
  3. 與普通for循環(huán)的區(qū)別:增強For循環(huán)有遍歷對象,普通for循環(huán)沒有遍歷對象;

對于實現(xiàn)了RandomAccess接口的集合類,推薦使用普通for,這種方式faster than Iterator.next

The RandomAccess interface identifies that a particular java.util.List implementation has fast random access. (A more accurate name for the interface would have been "FastRandomAccess.") This interface tries to define an imprecise concept: what exactly is fast? The documentation provides a simple guide: if repeated access using the List.get( ) method is faster than repeated access using the Iterator.next( ) method, then the List has fast random access. The two types of access are shown in the following code examples.

參考資料

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容