JCF之迭代器

迭代器概述

迭代器提供一种方法顺序访问一个聚合对象中的各个元素,而又不会暴露该对象的内部实现。

JCF中的容器和算法是分开的,使二者联系起来的就是迭代器了。

下面这段代码演示了迭代器的使用:

public class TestIterator {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add("aaa");
		list.add(new TestIterator());
		list.add(5);
		Iterator it = list.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

运行结果:

aaa

TestIterator@35ce36

5

 通过迭代器可以遍历访问list中的每个元素。


JCF中迭代器的设计

需要提到两个接口:

Iterator接口:

Java.util;
public interface Iterator<E> {
boolean hasNext();
E next();
    void remove();
}

Iterable接口

package java.lang;
import java.util.Iterator;
public interface Iterable<T> {
         //这个方法的返回值是一个迭代器对象引用
    Iterator<T> iterator();
}

这两个接口就是JCF迭代器设计的基石。Iterator接口定义了一个迭代器最基本的方法:判断是否还有元素、得到下一个元素。 Iterable接口定义了一个方法,该方法的返回值是一个迭代器对象的应用。

有了这个基石之后,就好办了。下面通过ArrayList的迭代器实现来一探究竟。

public class ArrayList<E> extends AbstractList<E>
        Implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
//并没有得到Iterator对象的方法
     .......................
}

ArrayList的源码中并没有找到Iterator的实现,从其定义中可以看出,ArrayList继承自AbstractList

来看看AbstractList

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

  protected transient int modCount = 0;

//创建迭代器的方法
   public Iterator<E> iterator() {
	     return new Itr();
    }
//通过内部类来实现迭代器
 private class Itr implements Iterator<E> {
            //下一次调用next返回的元素的索引。
	int cursor = 0;
           //最近一次调用next或previous返回的索引
	int lastRet = -1;

	int expectedModCount = modCount;

	public boolean hasNext() {
            return cursor != size();
	}
        //得到下一个元素
	public E next() {
            checkForComodification();
	    try {
		E next = get(cursor);
		lastRet = cursor++;
		return next;
	    } catch(IndexOutOfBoundsException e) {
		checkForComodification();
		throw new NoSuchElementException();
	    }
	}
          //删除cursor当前指向的元素
	public void remove() {
	    if (lastRet == -1)
		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();
	}
    }
}

AbstractList是为了将各个具体容器角色的公共部分提取出来而存在的。 可以看出,它是通过使用内部类来实现迭代器的。

通过以上结合实现源码的分析可以对JCF的迭代器设计总结如下:JCF定义了 Iterable接口,该接口中有一个获得迭代器的方法,

容器类通过实现这个接口来提供迭代器获取方法,当然不同的容器类实现方式可能不一样。

这里只是对JCF迭代器的初探,在后面的篇幅中还会有补充。


迭代器模式(摘自大话设计模式)

迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象中的内部表示。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值