1、在JDK5之前对于数组或者list的遍历需要根据长度,以及下标进行遍历于是就有了其遍历方式
List<String> list = new ArrayList<String>();
for (int index = 0; index < list.size(); index++ ) {
String str = list.get(index);
System.out.println("str: " + str);
}
2、在JDK5之后引入了:增强特性使list的遍历,进行改变
List<String> list = new ArrayList<String>();
for (String str : list){
System.out.println("str:" + str);
}
3、反编译class文件可以看到增强for循环会被编译器自动处理如下代码:
List<String> list = new ArrayList<String>();
Iterator var4 = list.iterator();
while(var4.hasNext()) {
str = (String)var4.next();
System.out.println("str:" + str);
}
即JDK在编译java文件的时候会将:符号以JDK的特性进行转换成list的迭代器,接着通过获取迭代器的下一元素处理数据
在ArrayList类的里面存着一个内部类Itr 实现了Iterator的接口
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
迭代器的原理是通过记录上一次读取数据的下标,以及下一次要下标,从而通过cursor和lastRet直接对集合的元素进行访问