Iterator原理(jdk1.8)
来源:互联网 发布:杭州java培训班包住 编辑:程序博客网 时间:2024/06/05 17:46
Iterator用于遍历集合中的元素,适用于不知道集合内部结构的情况。用户不再与集合类交互,而是与Iterator交互,其清楚知道集合类的内部状态,通过控制iterator达到遍历集合的目的。
Iterator<E>接口:
public interface Iterator<E> { boolean hasNext(); E next(); default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); }}
如ArrayList中的私有类Itr实现Iterator<E>接口:
private class Itr implements Iterator<E> { 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 != size; } @SuppressWarnings("unchecked") 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]; } 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(); } } //forEachRemaining方法此处略过 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
注意最后一个函数checkForComdification,检测ConcurrentModificationException异常。
反向输出也可以:
public interface ListIterator<E> extends Iterator<E>
ListIterator接口继承Iterator接口,实现从后往前遍历。(注意只有List集合有)
阅读全文
0 0
- Iterator原理(jdk1.8)
- Java_HashMap的工作原理(Jdk1.8)
- Iterator原理
- Jdk1.8中的HashMap实现原理
- Jdk1.8中的LinkHashMap实现原理
- Jdk1.8中的HashMap实现原理
- Jdk1.8中的HashMap实现原理
- jdk1.8中ConcurrentHashMap的实现原理
- HashMap的工作原理 - JDK1.8
- jdk1.8中ConcurrentLinkedQueue的实现原理
- JDK1.8中 HashMap实现原理
- jdk1.8中ConcurrentHashMap的实现原理
- 【Java并发】- ConcurrentHashMap原理解析(JDK1.8)
- Jdk1.8中的HashMap实现原理
- Jdk1.8中的HashMap实现原理
- jdk1.8中ConcurrentHashMap的实现原理
- 解析java iterator 原理
- Iterator原理及实现
- Java数据结构之链表
- C++中调用main函数
- 2017 ACM-ICPC 亚洲区(西安赛区)网络赛 Barty's Computer(暴力+hash)
- 自定义配置数据源 DataSource
- Java之——内存溢出案例
- Iterator原理(jdk1.8)
- Java实现选择排序和冒泡排序
- 枚举法填运算符
- Java多线程看我这一篇就足够了
- JavaScript-2-2:DOM(重点),封装类
- 利用DOM实现图书馆管理系统
- 密码锁(3602017秋招真题)
- 详谈Android apk打包:关于APK数字签名详解介绍
- iOS 在XCode中upload 成功,但是在itunes connect 一直看不到