java.lang.Iterable

从jdk1.5 java.lang包增加了这个接口。

实现这个接口允许对象成为 "foreach" 语句的目标,即增强的for循环。

然而此接口中只有一个接口类方法。

  /**
     * Returns an iterator over a set of elements of type T.
     *
     * @return an Iterator.
     */
    Iterator iterator();

实现这个接口很多,比如ArrayList、LinkedHashSet, LinkedList等等

ArrayList中有一个内部类实现了Iterator:

  public Iterator iterator() {
        return new Itr();
    }

  private class Itr implements Iterator {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

.......

所以使用for循环与使用迭代器iterator是有很明显的区别的:

1、iterator可以动态的移除元素,不用维护元素小标,但是for循环不行。

2、采用ArrayList对随机访问比较快,而for循环中的get()方法,采用的即是随机访问的方法,因此在ArrayList里,for循环较快。

3、采用LinkedList则是顺序访问比较快,iterator中的next()方法,采用的即是顺序访问的方法,因此在LinkedList里,使用iterator较快。

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0