Java集合框架中迭代器Iterator解析

网友投稿 201 2023-06-01


Java集合框架中迭代器Iterator解析

java里面的数组数据可以通过索引来获取,那么对象呢?也是通过索引吗?今天我们就来分析一下Java集合中获取集合对象的方法迭代-Iterator。

本篇文章主要分析一下Java集合框架中的迭代器部分,Iterator,该源码分析基于JDK1.8,分析工具,androidStudio,文章分析不足之处,还请指正!

一、简介

我们常常使用 JDK 提供的迭代接口进行 Java 集合的迭代。

Iterator iterator = list.iterator();

while(iterator.hasNext()){

String string = iterator.next();

//do something

}

上面便是迭代器使用的基本模板,迭代其实我们可以简单地理解为遍历,是一个标准化遍历各类容器里面的所有对象的方法类。它总是控制 Iterator,向它发送”向前”,”向后”,”取当前元素”的命令,就可以间接遍历整个集合。在 Java 中 Iterator 为一个接口,它只提供了迭代了基本规则:

public interface Iterator {

//判断容器内是否还有可供访问的元素

boolean hasNext();

//返回迭代器刚越过的元素的引用,返回值是 E

E next();

//删除迭代器刚越过的元素

default void remove() {

throw new UnsupportedOperationException("remove");

}

}

上面便是迭代器的基本申明,我们通过具体的集合来分析。

二、集合分类

2.1 ArrayList的Iterator

我们通过分析ArrayList的源码可以知道,在 ArrayList 内部首先是定义一个内部类 Itr,该内部类实现 Iterator 接口,如下:

private class Itr implements Iterator {

//....

}

在内部类实现了Iterator接口,而ArrayList的Iterator是返回的它的内部类Itr,所以我们主要看看Itr是如何实现的。

public Iterator iterator() {

return new Itr();

}

接下来我们分析一下它的内部类Itr的实现方式。

private class Itr implements Iterator {

protected int limit = ArrayList.this.size;

int cursor; // index of next element to return

int lastRet = -1; // index of last element returned; -1 if no such

int expectedModCount = modCount;

public boolean hasNext() {

return cursor < limit;

}

@SuppressWarnings("unchecked")

public E next() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

int i = cursor;

if (i >= limit)

throw new NoSuchElementException();

Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length)

throw new ConcurrentModificationException();

cursor = i + 1;

return (E) elementData[lastRet = i];

}

public void remove() {

if (lastRet < 0)

throw new IllegalStateException();

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

try {

ArrayList.this.remove(lastRet);

cursor = lastRet;

lastRet = -1;

expectedModCount = modCount;

limit--;

} catch (IndexOutOfBoundsException ex) {

throw new ConcurrentModificationException();

}

}

@Override

@SuppressWarnings("unchecked")

public void forEachRemaining(Consumer super E> consumer) {

Objects.requireNonNull(consumer);

final int size = ArrayList.this.size;

int i = cursor;

if (i >= size) {

return;

}

final Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length) {

throw new ConcurrentModificationException();

}

while (i != size && modCount == expectedModCount) {

consumer.accept((E) elementData[i++]);

}

// update once at end of iteration to reduce heap write traffic

cursor = i;

lastRet = i - 1;

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

}

}

首先我们来分析一下定义的变量:

protected int limit = ArrayList.this.size;

int cursor; // index of next element to return

int lastRet = -1; // index of last element returned; -1 if no such

int expectedModCount = modCount;

其中,limit是当前ArrayList的大小,cursor代表的是下一个元素的索引,而lastRet是上一个元素的索引,没有的话就返回-1,expectedModCount没什么多大用处。我们接着分析看迭代的时候怎么判断有没有后继元素的。

public boolean hasNext() {

return cursor < limit;

}

很简单,就是判断下一个元素的索引有没有到达数组的容量大小,达到了就没有了,到头了!

接着,我们在分析一下获取当前索引的元素的方法next

public E next() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

int i = cursor;

if (i >= limit)

throw new NoSuchElementException();

Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length)

throw new ConcurrentModificationException();

cursor = i + 1;

return (E) elementData[lastRet = i];

}

在next方法中为什么要判断modCount呢?即用来判断遍历过程中集合是否被修改过。modCount 用于记录 ArrayList 集合的修改次数,初始化为 0,,每当集合被修改一次(结构上面的修改,内部update不算),如 add、remove 等方法,modCount + 1,所以如果 modCount 不变,则表示集合内容http://没有被修改。该机制主要是用于实现 ArrayList 集合的快速失败机制,在 Java 的集合中,较大一部分集合是存在快速失败机制的。所以要保证在遍历过程中不出错误,我们就应该保证在遍历过程中不会对集合产生结构上的修改(当然 remove 方法除外),出现了异常错误,我们就应该认真检查程序是否出错而不是 catch 后不做处理。上面的代码比较简单,就是返回索引处的数组值。

对于ArrayList的迭代方法,主要是判断索引的值和数组的大小进行比较,看看还没有数据可以遍历了,然后再依次获取数组中的值,而已,主要抓住各个集合的底层实现方式即可进行迭代。

接下来我们在分析一下HashMap的Iterator的方法,其他方法类似,只要抓住底层实现方式即可。

2.2 HashMap的Iterator

在HashMap中,也有一个类实现了Iterator接口,只不过是个抽象类,HashIterator,我们来看看它的实现方式。

private abstract class HashIterator implements Iterator {

HashMapEntry next; // next entry to return

int expectedModCount; // For fast-fail

int index; // current slot

HashMapEntry current; // current entry

HashIterator() {

expectedModCount = modCount;

if (size > 0) { // advance to first entry

HashMapEntry[] t = table;

while (index < t.length && (next = t[index++]) == null)

;

}

}

public final boolean hasNext() {

return next != null;

}

final Entry nextEntry() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

HashMapEntry e = next;

if (e == null)

throw new NoSuchElementException();

if ((next = e.next) == null) {

HashMapEntry[] t = table;

while (index < t.length && (next = t[index++]) == null)

;

}

current = e;

return e;

}

public void remove() {

if (current == null)

throw new IllegalStateException();

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

Object k = current.key;

current = null;

HashMap.this.removeEntryForKey(k);

expectedModCount = modCount;

}

}

同样,它也定义了一个变量

HashMapEntry next; // next entry to return

int expectedModCount; // For fast-fail

int index; // current slot

HashMapEntry current; // current entry

next代表下一个entry的节点,expectedModCount同样是用于判断修改状态,用于集合的快速失败机制。index代表当前索引,current当前所索引所代表的节点entry,我们来看看如何判断是否还有下一个元素的值的。

public final boolean hasNext() {

return next != null;

}

很简单就是判断next是否为null,为null的话就代表没有数据了。

接着分析获取元素的方法

final Entry nextEntry() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

HashMapEntry e = next;

if (e == null)

throw new NoSuchElementException();

// 一个Entry就是一个单向链表

// 若该Entry的下一个节点不为空,就将next指向下一个节点;

// 否则,将next指向下一个链表(也是下一个Entry)的不为null的节点。

if ((next = e.next) == null) {

HashMapEntry[] t = table;

while (index < t.length && (next = t[index++]) == null)

;

}

current = e;

return e;

}

以上便是一些具体集合实例的迭代方法实现原理,同理可以分析其他集合的实现方式。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java实现读取文章中重复出现的中文字符串
下一篇:详解vue事件对象、冒泡、阻止默认行为
相关文章

 发表评论

暂时没有评论,来抢沙发吧~