迭代器简述
迭代器(Iterator)是一种设计模式、提供了一种方法,来对集合、容器进行遍历的方式,不需要关注底层数据结构和数据类型,来达到底层和上层遍历解耦的目的。
简单来说呢,迭代器就是遍历集合的一种方式,并且必须依赖于集合而存在!
但是他的底层实现还是不容易想通的,所以下面通过源码和我个人的理解来看一下啦~
方法详解
Iterator里面有三个方法:
- boolean hasNext() :判断集合是否还有元素; true表示还存在元素 ,false表示不存在元素
- E next():返回当前数据
- void remove():删除元素
因为Iterator是一个接口,所以以ArrayList中Iterator的源码为例进行分析
private class Itr implements Iterator<E> {
int cursor; // 表示下一个要访问的元素的索引
int lastRet = -1; //表示上一个访问的元素的索引
int expectedModCount = modCount; //版本号
//表示对ArrayList修改次数的期望值,它的初始值为modCount
//判断集合是否还有元素
public boolean hasNext() {
return cursor != size; //当前迭代的位置不是数组的最大容量值就返回true
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification(); //检查版本号是否一样,是否会产生并发异常
int i = cursor;
if (i >= size) //i大于或等于集合中的元素个数
throw new NoSuchElementException(); //抛异常
Object[] elementData = ArrayList.this.elementData;
//如果在上一个if没有抛出异常,那么说明i不大于size
//按理不会出现i大于数组长度的问题
//但是如果集合发生了改变,modCount和expectedModCount的值不一致,会抛一个并发性异常
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1; //下一个hasNext访问的下标
return (E) elementData[lastRet = i]; //返回上一个hasNext访问的元素
}
//删除元素
public void remove() {
if (lastRet < 0) //删除的下标不合法
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet; //cursor移到删除的下标处
lastRet = -1; //lastRet设为默认值,所以每次remove前必须调用next方法
expectedModCount = modCount; //删完后使版本号一致
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount) //modCount和expectedModCount的值不一致
throw new ConcurrentModificationException(); //并发异常
}
}
注意事项
- 在使用next()方法前必须调用hasNext()方法
- 使用remove()方法前必须调用next()方法
迭代器使用实例
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(5);
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()){
Integer value = iterator.next();
System.out.print(value+" ");
}
System.out.println();
}
对集合进行遍历时还有另外两种方法
1.通过for遍历
//通过for遍历
for (int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i)+" ");
}
System.out.println();
2.增强for循环
//增强for循环--》底层是通过迭代器实现的
for (Integer i :arrayList) {
System.out.print(i+" ");
}
System.out.println();
并发异常
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(5);
Iterator<Integer> iterator1 = arrayList.iterator();
while (iterator1.hasNext()){
Integer value = iterator1.next();
if (value == 3){
arrayList.remove(Integer.valueOf(3)); //修改了modCount版本号
}
System.out.print(value+" ");
}
在上面这种情况下程序就会抛出并发异常
原因:集合本身修改会引起modCount版本号修改,而迭代器本身的版本号副本并未改变,因此会抛出该异常
对并发异常的详细理解,可以参考此链接
[https://www.cnblogs.com/dolphin0520/p/3933551.html](博主讲的很清楚)