现在的位置: 首页 > 综合 > 正文

java JDK源码中的Iterator

2017年10月24日 ⁄ 综合 ⁄ 共 2047字 ⁄ 字号 评论关闭

Iterator的意思是迭代器。

在JDK源码中,Iterator是一个接口。

 

源码中,实现了Iterator接口的类,有很多:见图

 

1) java.util.*包中,所熟悉的一些Collection子类:AbstractList HashMap Hashtable LinkedHashMap LindedList TreeMap等;

2) java.util.concurrent*包中,诸如 ArrayBlockingQueue ConcurrentHashMap ConcurrentLinkedQueue等

3) javax.imageio.*包,javax.print.*包,javax.xml.*包中都存在这样的类(who implemented Iterator接口)

迭代器相关的接口有两个:Iterator 与 Iterable

 

从名字中,就能猜出它两啥用途:

Iterator意思为迭代器,Iterator及其子类通常是迭代器/迭代子本身的结构与方法;

Iterable意为可迭代的,那些想用到迭代器功能的其它类,如AbstractList HashMap等,需要实现该接口。

 

细看下两个接口文件:

 

Iterator.java  (只有三个方法)

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

Iterable.java   (只有一个方法)

public interface Iterable<T> {  
    Iterator<T> iterator();  
}  

通常的用法是:

某个类A(如 AbstractList )想使用迭代器,则它的类声明需是:class A implement Iterable

那么类A实现中,要实现Iterable接口中的唯一方法:Iterator<T> iterator();

这个方法用于返回一个迭代器/迭代子,即Iterator接口及其子类;

class A implement Iterable  
{  
    Iterator<T> iterator() {...}  
    class S implement Iterator<E>   
    {  
        boolean hasNext() {....}  
        E next() {....}  
        void remove() {....}  
    }  
}  

另外一个类B (如HashMap)也想使用迭代器,则依葫芦画瓢,方法、类声明啥的都一样,只是方法体不同。

所以,若A类的一个对象a想使用迭代器功能,则需要:

1) 获取迭代器对象: Iterator<E> iter = a.iterator();

2) 然后可以使用迭代器的三个方法进行迭代操作:  iter.hasNext()     iter.next()     iter.remove()

 

 

举例,看看AbstractList类:

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {  
  
    protected AbstractList() {  
    }  
    
    ...  
  
    public Iterator<E> iterator() {  
    return new Itr();  
    }  
  
    private class Itr implements Iterator<E> {  
       
    int cursor = 0;  
    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();  
        }  
    }  
  
    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();  
    }  
    }  
}  

转载自:http://suselinux.iteye.com/blog/1340353

抱歉!评论已关闭.