Iterable java

Iterable

iterable接口的源码:

package java.lang;

import java.util.Iterator;

/**
 * Implementing this interface allows an object to be the target( 目标) of
 * the "foreach" statement.
 *
 * @param <T> the type of elements returned by the iterator
 *
 * @since 1.5
 */
public interface Iterable<T> {

    /**
     * Returns an iterator over a set of elements of type T.
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();
}
Iterable这个接口只有一个方法,就是iterator,并且指示返回Iterator对象

Iterator

Iterator接口

package java.util;

/**
 * An iterator over a collection.  {@code Iterator} takes the place of
 * {@link Enumeration} in the Java Collections Framework.  Iterators
 * differ from enumerations in two ways:
 *
 * <ul>
 *      <li> Iterators allow the caller to remove elements from the
 *           underlying collection during the iteration with well-defined
 *           semantics.
 *      <li> Method names have been improved.
 * </ul>
 *
 * <p>This interface is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @param <E> the type of elements returned by this iterator
 *
 * @author  Josh Bloch
 * @see Collection
 * @see ListIterator
 * @see Iterable
 * @since 1.2
 */
public interface Iterator<E> {
    /**
     * Returns {@code true} if the iteration has more elements.
     * (In other words, returns {@code true} if {@link #next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
    boolean hasNext();

    /**
     * Returns the next element in the iteration.
     *
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iteration has no more elements
     */
    E next();

    /**
     * Removes from the underlying collection the last element returned
     * by this iterator (optional operation).  This method can be called
     * only once per call to {@link #next}.  The behavior of an iterator
     * is unspecified if the underlying collection is modified while the
     * iteration is in progress in any way other than by calling this
     * method.
     *
     * @throws UnsupportedOperationException if the {@code remove}
     *         operation is not supported by this iterator
     *
     * @throws IllegalStateException if the {@code next} method has not
     *         yet been called, or the {@code remove} method has already
     *         been called after the last call to the {@code next}
     *         method
     */
    void remove();
}
这个接口就只有三个方法:
判断有没有下一个元素:hasNext()
返回下一个元素:next()
移除元素:remove

集合类的根接口Collection

 Collection接口是所有集合类的根类型。它的一个主要的接口方法是:
boolean add(Object c)
   add()方法将添加一个新元素。注意这个方法会返回一个boolean,但是返回值不是表示添加成功与否。仔细阅读doc可以看到,Collection规定:如果一个集合拒绝添加这个元素,无论任何原因,都必须抛出异常。这个返回值表示的意义是add()方法执行后,集合的内容是否改变了(就是元素有无数量,位置等变化),这是由具体类实现的。即:如果方法出错,总会抛出异常;返回值仅仅表示该方法执行后这个Collection的内容有无变化( true  if this collection changed as a result of the call)。

   类似的还有:

boolean addAll(Collection c);
boolean remove(Object o);
boolean removeAll(Collection c);
boolean remainAll(Collection c);

   Object[] toArray()方法很简单,把集合转换成数组返回。Object[] toArray(Object[] a)方法就有点复杂了,首先,返回的Object[]仍然是把集合的所有元素变成的数组,但是类型和参数a的类型是相同的,比如执行:
String[] o = (String[])c.toArray(new String[0]);
   得到的o实际类型是String[]。

   其次,如果参数a的大小装不下集合的所有元素,返回的将是一个新的数组。如果参数a的大小能装下集合的所有元素,则返回的还是a,但a的内容用集合的元素来填充。尤其要注意的是,如果a的大小比集合元素的个数还多,a后面的部分全部被置为null。

   最后一个最重要的方法是iterator(),返回一个Iterator(迭代子),用于遍历集合的所有元素。

  用Iterator模式实现遍历集合

 
   Iterator模式是用于遍历集合类的标准访问方法。它可以把访问逻辑从不同类型的集合类中抽象出来,从而避免向客户端暴露集合的内部结构。

   例如,如果没有使用Iterator,遍历一个数组的方法是使用索引:

for(int i=0; i<array.size(); i++) { ... get(i) ... }
   而访问一个链表(LinkedList)又必须使用while循环:

while((e=e.next())!=null) { ... e.data() ... }
   以上两种方法客户端都必须事先知道集合的内部结构,访问代码和集合本身是紧耦合,无法将访问逻辑从集合类和客户端代码中分离出来,每一种集合对应一种遍历方法,客户端代码无法复用。

   更恐怖的是,如果以后需要把ArrayList更换为LinkedList,则原来的客户端代码必须全部重写。

   为解决以上问题,Iterator模式总是用同一种逻辑来遍历集合:

for(Iterator it = c.iterater(); it.hasNext(); ) { ... }
   奥秘在于客户端自身不维护遍历集合的"指针",所有的内部状态(如当前元素位置,是否有下一个元素)都由Iterator来维护,而这个Iterator由集合类通过工厂方法生成,因此,它知道如何遍历整个集合。

   客户端从不直接和集合类打交道,它总是控制Iterator,向它发送"向前","向后","取当前元素"的命令,就可以间接遍历整个集合。

   首先看看java.util.Iterator接口的定义:
public interface Iterator {
  boolean hasNext();
  Object next();
  void remove();
}

   依赖前两个方法就能完成遍历,典型的代码如下:
for(Iterator it = c.iterator(); it.hasNext(); ) {
  Object o = it.next();
  // 对o的操作...
}

   在JDK1.5中,还对上面的代码在语法上作了简化:

// Type是具体的类型,如String。
for(Type t : c) {
// 对t的操作...
}

   每一种集合类返回的Iterator具体类型可能不同,Array可能返回ArrayIterator,Set可能返回SetIterator,Tree可能返回TreeIterator,但是它们都实现了Iterator接口,因此,客户端不关心到底是哪种Iterator,它只需要获得这个Iterator接口即可,这就是面向对象的威力。

  Iterator源码剖析

 让我们来看看AbstractList如何创建Iterator。首先AbstractList定义了一个内部类(inner class):
private class Itr implements Iterator {
...
}

   而iterator()方法的定义是:
public Iterator iterator() {
  return new Itr();
} 

   因此客户端不知道它通过Iterator it = a.iterator();所获得的Iterator的真正类型。

   现在我们关心的是这个申明为private的Itr类是如何实现遍历AbstractList的:

private class Itr implements Iterator {
  int cursor = 0;
  int lastRet = -1;
  int expectedModCount = modCount;
} 

   Itr类依靠3个int变量(还有一个隐含的AbstractList的引用)来实现遍历,cursor是下一次next()调用时元素的位置,第一次调用next()将返回索引为0的元素。lastRet记录上一次游标所在位置,因此它总是比cursor少1。

   变量cursor和集合的元素个数决定hasNext():
public boolean hasNext() {
  return cursor != size();
} 
  方法next()返回的是索引为cursor的元素,然后修改cursor和lastRet的值:
public Object next() {
  checkForComodification();
  try {
   Object next = get(cursor);
   lastRet = cursor++;
   return next;
  } catch(IndexOutOfBoundsException e) {
   checkForComodification();
   throw new NoSuchElementException();
  }
}
 expectedModCount表示期待的modCount值,用来判断在遍历过程中集合是否被修改过。AbstractList包含一个modCount变量,它的初始值是0,当集合每被修改一次时(调用add,remove等方法),modCount加1。因此,modCount如果不变,表示集合内容未被修改。

   Itr初始化时用expectedModCount记录集合的modCount变量,此后在必要的地方它会检测modCount的值:

final void checkForComodification() {
  if (modCount != expectedModCount)
   throw new ConcurrentModificationException();
} 

   如果modCount与一开始记录在expectedModeCount中的值不等,说明集合内容被修改过,此时会抛出ConcurrentModificationException。

   这个ConcurrentModificationException是RuntimeException,不要在客户端捕获它。如果发生此异常,说明程序代码的编写有问题,应该仔细检查代码而不是在catch中忽略它。

   但是调用Iterator自身的remove()方法删除当前元素是完全没有问题的,因为在这个方法中会自动同步expectedModCount和modCount的值:
public void remove() {
...
AbstractList.this.remove(lastRet);
...
// 在调用了集合的remove()方法之后重新设置了expectedModCount:
expectedModCount = modCount;
...
}

   要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。

   最后给个完整的示例:
Collection c = new ArrayList();
c.add("abc");
c.add("xyz");
for(Iterator it = c.iterator(); it.hasNext(); ) {
  String s = (String)it.next();
  System.out.println(s);
} 

   如果你把第一行代码的ArrayList换成LinkedList或Vector,剩下的代码不用改动一行就能编译,而且功能不变,这就是针对抽象编程的原则:对具体类的依赖性最小。

转自:http://hi.baidu.com/xhxzdjtppebaprq/item/9f7c061e30323816e2f986bf

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值