文章目录
1. ListInterator迭代器游标的逻辑与底层原理
首先我们先引入两个变量:
- cursor:表示下一个元素的索引位置
- lastRet:表示上一个元素的索引位置
1.1 获取迭代器后:curse = 0;lastRet = -1
1.2 next()方法
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];
}
next()执行过程:
- curse = curse+1;
- lastRet = 原来的curse;
- 返回lastRet处元素
1.3 previous()方法
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
previous()执行过程:
- cursor=cursor-1;
- lastRet=cursor;
- 返回lastRet处元素
1.4 add(E e)
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
add(E e)执行过程:
- 在curse处创建元素,然后后续元素后移(此时两个变量的指向第一个元素可能改变);
- curse = curse+1;
- lastRet = -1;
1.5 remove()
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();
}
}
remove()执行过程:
- 移除lastRet处元素(此时两个变量的指向第几个元素可能改变);
- cursor = lastRet;
- lastRet = -1;
1.6 set(E e):只看lastRet
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
remove()执行过程:只看lastRet
2. 结论总结
获取迭代器后 | curse = 0; | lastRet = -1 | |
---|---|---|---|
next() | curse = curse+1 | lastRet = 原来的curse | 返回lastRet处元素 |
previous() | cursor=cursor-1 | lastRet=cursor | 返回lastRet处元素 |
add(E e) | 在curse处创建元素,其余元素后移(此时两个变量的指向第一个元素可能改变) | curse = curse+1 | lastRet = -1 |
remove() | 移除lastRet处元素(此时两个变量的指向第几个元素可能改变) | cursor = lastRet | lastRet = -1 |
set(E e) | 只看lastRet |
3. 例子
3.1 例子1
注意:图中左边箭头表示curse;右边箭头表示lastRet