Iterator接口:
所有實現了Collection接口的容器類都有一個iterator方法用以返回一個實現Iterator接口的對象
Iterator對象稱作爲迭代器,以方便的對容器內元素的遍歷操作
Iterator接口定義瞭如下方法:
1. boolean hashNext(); //判斷是否有元素沒有被遍歷
2. Object next(); //返回遊標當前位置的元素並將遊標移動到下一個位置
3. void remove(); //刪除遊標左邊的元素,在執行完next之後該操作只能執行一次。
public class Test{
public static void main(String[] args) {
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
//通過索引遍歷List
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
//通過迭代器遍歷List
for(Iterator iter1 = list.iterator();iter1.hasNext();){
String str = (String) iter1.next();
System.out.println(str);
iter1.remove();
//iter1.remove();
}
System.out.println(list.size()+"******");
Set set = new HashSet();
set.add("高1");
set.add("高2");
set.add("高3");
//通過迭代器遍歷Set
// Iterator iter = set.iterator();
// while(iter.hasNext()){
for(Iterator iter = set.iterator();iter.hasNext();){
String str = (String) iter.next();
System.out.println(str);
}
}
}
list迭代器的源碼分析
private class Itr implements Iterator<E> {
int cursor = 0;
int lastRet = -1;
public boolean hasNext() {
return cursor != size();
}
public E next() {
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}