集合 java中的迭代器
来源:互联网 发布:公众号排版软件 编辑:程序博客网 时间:2024/05/22 12:07
今天学习了 集合,但是感觉对于迭代器不是 很明白,所以研究了一下!
在 JDK中
Collection作为集合的顶级容器, 她实现了Java.lang.Iterable 接口!
Iterable: 可迭代的, 想使用迭代功能的容器必须实现这个顶级接口,中的 iterator() 方法。
Iterator:迭代器. 每个容器的内部都有不同的迭代器实现。抽取出她们的共性,我们抽取出
Iterator 接口。
我们查看源码
Iterator:
public interface Iterator<E> { boolean hasNext(); E next(); void remove(); }
Iterable:
public interface Iterable<T> { /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ Iterator<T> iterator();}
1 如果AbstractList 类,要使用迭代器。 她必须实现 Iterable.
2 在AbstractList 代码中必须实现 Iterator<T> iterator(){};
返回 迭代器的接口或子类 引用。
2 在 AbstractList 代码中,定义一个内部类,实现 Iterator 接口。
制定自己的 迭代器实现!
AbstractList 源码实现:
<pre name="code" class="html">public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.)
构造函数 protected AbstractList() { }
实现 Iterable 接口的方法, public Iterator<E> iterator() { return new Itr(); }
内部类 定义自己的 迭代器的 具体实现 private class Itr implements Iterator<E> { /** * Index of element to be returned by subsequent call to next. */ 当前索引 int cursor = 0; /** * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. */ 上一次的索引位置 int lastRet = -1; /** * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount;判断是否 有下一个元素 public boolean hasNext() { return cursor != size(); }获取下一个元素 public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }去掉元素 public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } }检查异常 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }}
1 0
- 集合 java中的迭代器
- java集合中的迭代器求解!
- Java中的集合的迭代器
- java 中的集合和迭代器
- java中的集合类 以及 迭代器
- java集合类中的迭代器模式
- java中的集合,迭代器的使用以及java中的异常
- JAVA中的集合类
- JAVA中的集合类
- JAVA中的集合类
- JAVA中的集合类
- JAVA中的集合类
- JAVA中的集合类 - -
- JAVA中的集合类
- java中的集合类
- Java中的集合类
- Java中的集合
- JAVA中的集合
- JavaScript的语句—判断,选择,循环
- httpclient解析网页,htmlparser获取制定元素
- NYOJ 528找球号(三)
- HDU 1789 Doing Homework again
- AWS - 手动创建VPC 公网,子网和NAT实例
- 集合 java中的迭代器
- Maven配置和初次使用
- 素数判定
- 2014杭电多校联合第三场The Great Pan模拟题
- 沐阳JP1081B USB转网口 内核选项
- windows server 2003访问局域网中共享文件
- 痴迷Linux(一)—初识篇
- 创建你的第一个安卓应用4 - 第四课 - 启动另外一个activity
- UITextField切换中文输入,选中所输入的中文时,iOS7不会调用textField:shouldChangeCharactersInRange:replacementString协议方法。