Iterator接口
Iterator接口,实现方法是对该集合的遍历,底层的foreach,就是使用的实现Iterator接口接口的方法。
Iterator接口的方法
next() :返回下一个元素,并且让游标和lastRet向后移动
hasNext():判断是否有下一个元素
remove():移除最后返回的元素。
tips:实现Iterator接口的方法后,返回的是iterator接口。
我们以ArrayList为例:
看一下ArraylList实现的Iterator的遍历方式
首先最开始的next指向的并不是第二个元素,而是第一个元素(底层是cursor指向,这里用next是为了更形象)
所以hasNext判断的就是next是否为null,
并且remove时,改变了集合的结构,所以在使用iterator进行集合遍历时,remove方法自己改变了ExceptCount的值。所以快速失败并不会在这里调用。
我们简单的用代码实现一下,使用Iterator来进行集合的遍历
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(10);
//接口不能被实例化,只能使用子类的实例
Iterator iterator = arrayList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
结果:
现在我们来实现以下快速失败机制,在进行遍历时,我们是不能对集合的结构有所改变。如果另一个线程改变里集合的结构,那么就会直接抛出异常。
但是如果调用iterator接口中的remove()方法就不会报错
注意虽然打印了1,但在这个集合中,1这个元素已经被移除了。
我们debug验证一下
最后,每一个集合类的实现iterator 的方式各不相同,例如ArrayList和LinkedList,在ArrayList遍历是依靠下标偏移,而LinkedList是依靠引用指向。并且有的集合还会对iterator在进行一次包装,例如HashMap。所以如果要去遍历集合,最终要是要了解源码的大概实现。
推荐使用iterator遍历格式
既然能使用 while 去遍历,那么同样可以写成 for 循环需遍历
ListIterator<Integer> iterator = arrayList.listIterator();
while(iterator.hasPrevious()){
System.out.print(iterator.previous() + " ");
}
//推荐写法
for (ListIterator iter = arrayList.listIterator(); iter.hasNext(); ){
System.out.println(iter.next());
}
这两种写法,打印结果是一摸一样的,但是,第一种写法,创建出来的iterator的这个对象并不会被回收,如果后续我们不再使用iterator去遍历,那么空间就会被浪费。第二种写法将iterator定义成了临时变量,所以当for循环结束,所占用的内存空间也随之释放。
扩展
ListIterator不仅可以向下遍历还可以向上遍历。
同样是基于cursor 和 lastRet。
我们可以向下遍历3个单位向上遍历2个单位。
ListIterator<Integer> iterator = arrayList.listIterator();
int i = 0;
while(iterator.hasNext()&&i<3){
System.out.print(iterator.next()+" ");
i++;
}
System.out.println();
while(iterator.hasPrevious()&& i >1){
System.out.print(iterator.previous() + " ");
i--;
}
结果:
注意:无论是hasNext(),还是hasPrevious(),他们都是基于cursor和lastRet的指针访问。
所以最初cursor = 0,lastRet = -1时,是没有办法做到向前遍历元素的。
ListIterator<Integer> iterator = arrayList.listIterator();
int i = 3;
while(iterator.hasPrevious()&& i >1){
System.out.print(iterator.previous() + " ");
i--;
}
结果: