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();
}
}