Iterator和Iterable接口

来源:互联网 发布:淘宝空间图片协议在哪 编辑:程序博客网 时间:2024/05/21 06:50
迭代器模式本质是将聚合对象的内容与遍历分开,所以使用者可以不用考虑聚合对象的底层实现(是用list存储还是用数组存储)而以一种统一的方式(Iterator)来遍历对象;而且可以利用筛选迭代器对对象进行过滤,只遍历符合条件的对象;迭代器的迭代策略(单向、双向等)可以灵活的修改。

为了利用迭代器模式,java中定义了一个Iterator迭代器接口和一个Iterable接口;Iterator迭代器中定义了遍历需要用到的方法,如next()、hasNext()、remove()方法;Iterable接口中声明了一个Iterator迭代器;

Iterator接口定义在java.util包中:
public interface Iterator<E> {    boolean hasNext();    E next();    void remove();}

实现Iterator接口的接口和类如下所示:
所有已知子接口:ListIterator<E>, XMLEventReader所有已知实现类:BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner

其中ListIterator接口在Iterable接口的基础上增加了前向遍历的方式,定义如下:
public interface ListIterator<E> extends Iterator<E> {    boolean hasNext();    E next();    boolean hasPrevious();    E previous();    int nextIndex();    int previousIndex();    void remove();    void set(E e);    void add(E e);}


Iterable接口定义在java.lang包中:
public interface Iterable<T> {    Iterator<T> iterator();}

实现了Iterable接口的接口和类如下:
所有已知子接口:BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Collection<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>所有已知实现类:AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue,
ArrayDeque, ArrayList, AttributeList, BatchUpdateException, BeanContextServicesSupport, BeanContextSupport,
 ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DataTruncation, 
DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet,
 LinkedList, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, RowSetWarning, SerialException,
 ServiceLoader, SQLClientInfoException, SQLDataException, SQLException, SQLFeatureNotSupportedException,
SQLIntegrityConstraintViolationException, SQLInvalidAuthorizationSpecException, SQLNonTransientConnectionException
, SQLNonTransientException, SQLRecoverableException, SQLSyntaxErrorException, SQLTimeoutException,
SQLTransactionRollbackException, SQLTransientConnectionException, SQLTransientException, SQLWarning, 
Stack, SyncFactoryException, SynchronousQueue, SyncProviderException, TreeSet, Vector

Collection接口继承了Iterable接口:(注意Collection是一个接口,而Collections是一个操作集合的工具类)
public interface Collection<E> extends Iterable<E> {}
Collection的几个子接口,如List、Set、Queue也都间接继承了Iterable接口。
Map接口没有继承Iteratale接口,但是Map的遍历访问可以通过获取Map的KeySet(keySet是一个set集合)来遍历Map。
public interface Map<K,V> {}

可以看出所有的集合类都是直接或间接继承了Iterable接口的,而Iterable接口中可以获得Iterator迭代器,这样保证了每个集合类的每个副本每次获得的Iterator都是从第一个元素开始遍历的,各个Iterator互不干扰。

另外,foreach的实现原理是编译器帮我们将遍历直接转换成了对集合iterator.next()的调用(可以使用foreach进行遍历集合都实现了Iterable接口),所以如果自定义类实现了Iterable接口并且实现了该接口中iterator()方法的具体定义,则可以通过foreach语法来遍历自定义的类



0 0