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);
}
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循环有一些差异
对于实现了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.