Java 增强for循环原理

在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的效率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值