Java中普通for循環和加強for循環的一些區別

Java中for的幾種常見形式

1.For loop using index.html

for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    body-of-loop
}
複製代碼

2.Loop using explicit iterator.java

for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    body-of-loop
}
複製代碼

3.Foreach loop over all elements in arr.數組

for (type var : coll) {
    body-of-loop
}
複製代碼

For循環用來處理哪些數據結構

1.數組數據結構

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);
}
複製代碼

2.實現了java.util.Iterator的類oracle

import java.util.Iterator;

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的一些區別

加強的for循環的底層使用迭代器來實現,因此它就與普通for循環有一些差別dom

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

對於實現了RandomAccess接口的集合類,推薦使用普通for,這種方式faster than Iterator.nextide

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.oop

參考資料

相關文章
相關標籤/搜索