Java 增强for循环原理

来源:互联网 发布:广数980tdb编程实例 编辑:程序博客网 时间:2024/06/05 20:38

在Java语言中循环遍历的方式有多种常见的有:for循环、增强for循环、while循环、do while循环、迭代器。

最近在学习java Collection集合的原理,发现了集合中增强for循环的实现原理,突然对曾经不懂的和懵懂的问题有了新的理解,在此记录一下,对于java初学者和想对深层理解的朋友有一定的帮助。

首先增强for循环是在JDK1.5中被加入使用。
1.5 及以上的编译器隐藏了基于iteration和下标遍历的内部实现。

废话不多说,先上一段简单的增强for循环的代码:

public static<AnyType> void print(Collection<AnyType> colls){    for(AnyType item : colls){        System.out.print(item);    }}

这里要提一句只有实现Iterable接口的那些类可以拥有增强for循环。

那么问题来了,为什么这么设计呢?

上一段Iterable接口的源码和注释先看一下

package java.lang;import java.util.Iterator;/** * Instances of classes that implement this interface can    * be used with the enhanced for loop. * @since 1.5 */public interface Iterable<T> {    /**     * Returns an {@link Iterator} for the elements in      * this object.     * @return An {@code Iterator} instance.     */    Iterator<T> iterator();}

然后再看Collection类的源码

package java.util;public interface Collection<E> extends Iterable<E> {    /**    ...    **/}

通过注释我们可以看出,Collection类有实现了Iterable这个接口才可以用增强for循环。
所以我们就可以想到所有实现Collection接口的类或其子类如ArrayList、LinkedList、LinkedHashSet等都可以使用增强for循环的。

再回到刚刚的问题,为什么这么设计?
带着问题我们先从实现原理分析:
以AbstractCollection.java为例

package java.util;public abstract class AbstractCollection<E> implements Collection<E> {    /**    ...    **/    /**     * Returns an instance of {@link Iterator} that may      * be used to access the     * objects contained by this {@code Collection}. The order in which the elements are     * returned by the {@link Iterator} is not defined unless the instance of the     * {@code Collection} has a defined order.  In that case, the elements are returned in that order.     * <p>     * In this class this method is declared abstract and has to be implemented     * by concrete {@code Collection} implementations.     *     * @return an iterator for accessing the {@code Collection} contents.     */    public abstract Iterator<E> iterator();}

AbstractCollection类实现了Iterable接口必须提供一个iterator的方法,该方法返回一个Iterator类型的对象。Iterator接口的思路是通过iterator方法,每个集合均可创建并返回给开发者一个实现Iterator接口的对象,并将当前位置的概念在对象内部存储下来。

Iterator接口源码

public interface Iterator<E> {    public boolean hasNext();    public E next();    public void remove();}
  • next()每次调用都给出集合的下一项。
  • hasNext()用来告诉是否存在下一项。
  • remove()删除有next()最新返回的项。

所以第一个增强for循环的代码可以写成

public static<AnyType> void print(Collection<AnyType> colls){    Iterator<AnyType> iterator = calls.iterator();    while(iterator.hasNext()){        AnyType anyType = iterator.next();        System.out.print();    }}

有以上可以看出增强for循环是基于Iterator来实现的。
由于增强for循环是基于Iterator实现的所以有些情况下增强for循环的执行效率会低于Iterator的效率。

拙见,有不足之处请指点。

1 0
原创粉丝点击