本文已收录在Github,关注我,紧跟本系列专栏文章,咱们下篇再续!
- 🚀 魔都架构师 | 全网30W技术追随者
- 🔧 大厂分布式系统/数据中台实战专家
- 🏆 主导交易系统百万级流量调优 & 车联网平台架构
- 🧠 AIGC应用开发先行者 | 区块链落地实践者
- 🌍 以技术驱动创新,我们的征途是改变世界!
- 👉 实战干货:编程严选网
0 常用JDK迭代接口
进行Java集合迭代:
Iterator iterator = list.iterator(); while (iterator.hasNext()) { String string = iterator.next(); //do something }
迭代可简单理解为遍历,是一个标准化遍历各类容器里面的所有对象的方法类。Iterator模式是用于遍历集合类的标准访问方法。它可以把访问逻辑从不同类型集合类中抽象出来,从而避免向客户端暴露集合内部结构。
1 没有迭代器时的处理
1.1 数组处理
int[] arrays = new int[10]; for(int i = 0 ; i < arrays.length ; i++){ int a = arrays[i]; // do sth }
ArrayList处理:
List<String> list = new ArrayList<String>(); for(int i = 0 ; i < list.size() ; i++){ String string = list.get(i); // do sth }
都需先知集合内部结构,访问代码和集合结构本身紧耦合,无法将访问逻辑从集合类和客户端代码中分离。同时每种集合对应一种遍历方法,客户端代码无法复用。
实际应用中,若需要将上面将两个集合进行整合,则很麻烦。所以为解决如上问题, Iterator 模式诞生了。 它总是用同一种逻辑遍历集合,从而客户端无需再维护集合内部结构,所有内部状态都由 Iterator 维护。客户端不直接和集合类交互,它只控制 Iterator,向它发送”向前”,”向后”,”取当前元素”的命令,即可实现对客户端透明地遍历整个集合。
2 java.util.Iterator
在 Java 中 Iterator 为一个接口,它只提供迭代的基本规则,在 JDK 中他是这样定义的:对 collection 进行迭代的迭代器。
package java.util; import java.util.function.Consumer; public interface Iterator<E> {
迭代器取代Java集合框架的Enumeration。
迭代器 V.S 枚举
- 迭代器允许调用者利用定义良好的语义在迭代期间,从迭代器所指向的 collection 移除元素
- 优化方法名
接口定义
public interface Iterator<E> { // 判断容器内是否还有可供访问的元素 boolean hasNext(); // 返回迭代器刚越过的元素的引用,返回值是 Object,需要强制转换成自己需要的类型 E next(); // 删除迭代器刚越过的元素 default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
一般只需用 next()、hasNext(),即可完成迭代:
for(Iterator it = c.iterator(); it.hasNext(); ) { Object o = it.next(); // do sth }
Iterator优点
无需知道集合内部结构。集合的内部结构、状态都由 Iterator 维护,通过统一方法 hasNext()、next()来判断、获取下一个元素,而不用关心具体内部实现。
3 各集合的 Iterator 实现
ArrayList内部实现采用数组,只需记录相应位置的索引。
ArrayList的Iterator
ArrayList内部先定义一个内部类 Itr,该内部类实现 Iterator 接口,如下:
// An optimized version of AbstractList.Itr private class Itr implements Iterator<E> {
ArrayList#iterator()返回这 Itr() 内部类
/** * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); }
成员变量
在 Itr 内部定义了三个 int 型的变量:
int cursor; // index of next element to return 下一个元素的索引位置 int lastRet = -1; // index of last element returned; -1 if no such 上一个元素的索引位置 int expectedModCount = modCount;
所以lastRet 一直比 cursor 小 1。所以 hasNext() 实现很简单:
public boolean hasNext() { return cursor != size; }
next()
返回 cursor 索引位置处的元素即可,再更新cursor、lastRet :
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 + 1 cursor = i + 1; // lastRet + 1 且返回cursor处元素 return (E) elementData[lastRet = i]; }
checkForComodification() 主要判断集合的修改次数是否合法,即判断遍历过程中集合是否被修改过。 modCount 用于记录 ArrayList 集合的修改次数,初始化为 0。每当集合被修改一次(结构上面的修改,内部update不算),如 add、remove 等方法,modCount + 1。 所以若 modCount 不变,则表示集合内容未被修改。该机制主要用于实现 ArrayList 集合的快速失败机制。所以要保证在遍历过程中不出错误,我们就应该保证在遍历过程中不会对集合产生结构上的修改(当然 remove 方法除外),出现了异常错误,我们就应该认真检查程序是否出错而不是 catch 后不做处理。
private void checkForComodification(final int expectedModCount) { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
remove()
调用 ArrayList 本身的 remove() 方法删除 lastRet 位置元素,然后修改 modCount 即可。
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(); } }
SubList.this#remove(lastRet)
public E remove(int index) { Objects.checkIndex(index, size); checkForComodification(); E result = root.remove(offset + index); updateSizeAndModCount(-1); return result; }
ArrayList#remove
public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }