Iterator、Iterable接口的使用及详解

Java集合类库将集合的接口与实现分离。同样的接口,可以有不同的实现。

Java集合类的基本接口是Collection接口。而Collection接口必须实现Iterator接口。

以下图表示集合框架的接口,java.lang以及java.util两个包里的。其他部分可以从左向右看,比如Collection的Subinterfaces有List,Set以及Queue等。

package java.util;

/**
 * An iterator over a collection.  Iterator takes the place of 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>.
 *
 * @author  Josh Bloch
 * @version %I%, %G%
 * @see Collection
 * @see ListIterator
 * @see Enumeration
 * @since 1.2
 */
public interface Iterator<E> {
    /**
     * Returns <tt>true</tt> if the iteration has more elements. (In other
     * words, returns <tt>true</tt> if <tt>next</tt> would return an element
     * rather than throwing an exception.)
     *
     * @return <tt>true</tt> if the iterator has more elements.
     */
    boolean hasNext();

    /**
     * Returns the next element (每一次迭代,the next element就是index为0的元素)in the iteration.
     *
     * @return the next element in the iteration.
     * @exception NoSuchElementException iteration has no more elements.
     */
    E next();

    /**
     *
     * Removes from the underlying collection the last element returned by the
     * iterator (optional operation).  This method can be called only once per
     * call to <tt>next</tt>.  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.
     *
     * @exception UnsupportedOperationException if the <tt>remove</tt>
     *          operation is not supported by this Iterator.

     * @exception IllegalStateException if the <tt>next</tt> method has not
     *          yet been called, or the <tt>remove</tt> method has already
     *          been called after the last call to the <tt>next</tt>
     *          method.
     */
    void remove();
}

以下例子是利用了Iterator接口的着三个方法,实现遍历ArrayList<String>类型。
一开始迭代器在所有元素的左边,调用next()之后,迭代器移到第一个和第二个元素之间,next()方法返回迭代器刚刚经过的元素
hasNext()若返回True,则表明接下来还有元素,迭代器不在尾部。
remove()方法必须和next方法一起使用,功能是去除刚刚next方法返回的元素

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ForEachDemo {
    public static void main(String... arg) {
        Collection<String> a = new ArrayList<String>();
        a.add("Bob");
        a.add("Alice");
        a.add("Lisy");

        Iterator<String> iterator = a.iterator();
        while (iterator.hasNext()) {
            String ele = iterator.next();
            System.out.println(ele);//Bob  Alice  Lisy
        }
        System.out.println(a);//[Bob, Alice, Lisy]
        iterator = a.iterator();
        iterator.next();
        iterator.remove();
        System.out.println(a);//[Alice, Lisy]
    }
}  

package java.lang;

import java.util.Iterator;

/** Implementing this interface allows an object to be the target of
 *  the "foreach" statement.
 * @since 1.5
 */
public interface Iterable<T> {

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

for-each循环可以与任何实现了Iterable接口的对象一起工作。
而Collection接口扩展了Iterable接口,故标准类库中的任何集合都可以使用for-each循环。

Collection接口

此接口的方法

public interface Collection<E>{......}

 
Modifier and Type Method and Description
boolean add(E e)

Ensures that this collection contains the specified element (optional operation).

boolean addAll(Collection<? extends E> c)

Adds all of the elements in the specified collection to this collection (optional operation).

void clear()

Removes all of the elements from this collection (optional operation).

boolean contains(Object o)

Returns true if this collection contains the specified element.

boolean containsAll(Collection<?> c)

Returns true if this collection contains all of the elements in the specified collection.

boolean equals(Object o)

Compares the specified object with this collection for equality.

int hashCode()

Returns the hash code value for this collection.

boolean isEmpty()

Returns true if this collection contains no elements.

Iterator<E> iterator()

Returns an iterator over the elements in this collection.

boolean remove(Object o)

Removes a single instance of the specified element from this collection, if it is present (optional operation).

boolean removeAll(Collection<?> c)

Removes all of this collection‘s elements that are also contained in the specified collection (optional operation).

boolean retainAll(Collection<?> c)

Retains only the elements in this collection that are contained in the specified collection (optional operation).

int size()

Returns the number of elements in this collection.

Object[] toArray()

Returns an array containing all of the elements in this collection.

<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

因为其中有一个返回值为Iterator<E>类型的iterator()方法,所以,Collection接口必须实现Iterator接口

实现Collection接口的每一个类都要实现以上众多方法,但开发者自己实现很麻烦。所以java提供了AbstractCollection类来编写具体的类。

java.util 
Interface Collection<E>

All Superinterfaces:
Iterable<E>
All Known Subinterfaces:
BeanContextBeanContextServicesBlockingDeque<E>, BlockingQueue<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>,SortedSet<E>
All Known Implementing Classes:
AbstractCollectionAbstractListAbstractQueueAbstractSequentialListAbstractSetArrayBlockingQueueArrayDequeArrayListAttributeListBeanContextServicesSupportBeanContextSupportConcurrentLinkedQueueConcurrentSkipListSetCopyOnWriteArrayListCopyOnWriteArraySet,DelayQueueEnumSetHashSetJobStateReasonsLinkedBlockingDequeLinkedBlockingQueueLinkedHashSetLinkedListPriorityBlockingQueue,PriorityQueueRoleListRoleUnresolvedListStackSynchronousQueueTreeSetVector

Collection接口有三个常用的子接口,分别是List,Set,Queue。

http://blog.csdn.net/xujinsmile/article/details/8543544

为什么一定要去实现Iterable这个接口呢? 为什么不直接实现Iterator接口呢?

看一下JDK中的集合类,比如List一族或者Set一族,
都是实现了Iterable接口,但并不直接实现Iterator接口。
仔细想一下这么做是有道理的。因为Iterator接口的核心方法next()或者hasNext()
依赖于迭代器的当前迭代位置的。
如果Collection直接实现Iterator接口,势必导致集合对象中包含当前迭代位置的数据(指针)。
当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。
除非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。
但即时这样,Collection也只能同时存在一个当前迭代位置。
而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。
多个迭代器是互不干扰的。
http://www.cnblogs.com/highriver/archive/2011/07/27/2077913.html

import java.util.Iterator;

public class ForEachAPIDemo {
    public static void main(String[] args) throws Exception {
        Students students = new Students(10);
        for (Student student : students) {
            System.out.println(student.getSid() + ":" + student.getName());
        }
    }
}

// 支持for each迭代循环的学生集合类
class Students implements Iterable<Student> {
    // 存储所有学生类的数组
    private Student[] students;

    // 该构造函数可以生成指定大小的学生类变量数组,并初始化该学生类变量数组
    public Students(int size) {
        students = new Student[size];
        for (int i = 0; i < size; i++) {
            students[i] = new Student(String.valueOf(i), "学生" + String.valueOf(i));
        }
    }

    @Override
    public Iterator<Student> iterator() {
        return new StudentIterator();
    }

    // 实现Iterator接口的私有内部类,外界无法直接访问
    private class StudentIterator implements Iterator<Student> {
        // 当前迭代元素的下标
        private int index = 0;

        // 判断是否还有下一个元素,如果迭代到最后一个元素就返回false
        public boolean hasNext() {
            return index != students.length;
        }

        @Override
        public Student next() {
            return students[index++];
        }

        // 这里不支持,抛出不支持操作异常
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}

class Student {
    private String sid;
    private String name;

    public Student(String sid, String name) {
        setSid(sid);
        setName(name);
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=‘" + sid + ‘\‘‘ +
                ", name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}
时间: 2024-08-13 05:14:37

Iterator、Iterable接口的使用及详解的相关文章

OpenCV学习C++接口 Mat像素遍历详解

OpenCV学习C++接口 Mat像素遍历详解 原文地址:https://www.cnblogs.com/zhehan54/p/8460602.html

Jmeter接口之响应断言详解

响应断言 : 对服务器的响应进行断言校验 Apply to 应用范围: main sample and sub sample, main sample only , sub-sample only , jmeter variable 关于应用范围,我们大多数勾选"main sample only" 就足够了,因为我们一个请求,实质上只有一个请求.但是当我们发一个请求时,可以触发多个服务器请求,类似于ajax那种,那么就有main sample 和 sub-sample之分了.此外,对于

Java学习之Iterator(迭代器)的一般用法和详解

迭代器(Iterator) 迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构.迭代器通常被称为"轻量级"对象,因为创建它的代价小. Java中的Iterator功能比较简单,并且只能单向移动: (1) 使用方法iterator()要求容器返回一个Iterator.第一次调用Iterator的next()方法时,它返回序列的第一个元素.注意:iterator()方法是java.lang.Iterable接口,被Collection继承

Java知多少(58)线程Runnable接口和Thread类详解

大多数情况,通过实例化一个Thread对象来创建一个线程.Java定义了两种方式: 实现Runnable 接口: 可以继承Thread类. 下面的两小节依次介绍了每一种方式. 实现Runnable接口 创建线程的最简单的方法就是创建一个实现Runnable 接口的类.Runnable抽象了一个执行代码单元.你可以通过实现Runnable接口的方法创建每一个对象的线程.为实现Runnable 接口,一个类仅需实现一个run()的简单方法,该方法声明如下:    public void run( )

EIGRP汇总后生成的Null0接口和路由黑洞详解

提到Null0接口,就顺便提一下路由黑洞.所谓黑洞路由,顾名思义他就是将所有无关路由吸入其中,使它们有来无回的路由 - 相当于洪水来临时,在洪水途经的路上附近挖一个不见底的巨大深坑,然后将洪水引入其中. 黑洞路由实际是一种特殊的静态路由,就是目的地址为该网段的数据报文到达设备之后,报文将被丢弃.路由黑洞最大的好处是充分利用了路由器的3层数据包转发能力,对系统负载影响非常小,将报文丢弃的操作不需要CPU进行什么专门的处理,所以处理大量的报文也不会消耗设备的CPU资源! 例如,admin建立一个路由

【python3+request】python3+requests接口自动化测试框架实例详解教程

转自:https://my.oschina.net/u/3041656/blog/820023 前段时间由于公司测试方向的转型,由原来的web页面功能测试转变成接口测试,之前大多都是手工进行,利用postman和jmeter进行的接口测试,后来,组内有人讲原先web自动化的测试框架移驾成接口的自动化框架,使用的是java语言,但对于一个学java,却在学python的我来说,觉得python比起java更简单些,所以,我决定自己写python的接口自动化测试框架,由于本人也是刚学习python,

python+requests接口自动化测试框架实例详解教程

转自https://my.oschina.net/u/3041656/blog/820023 摘要: python + requests实现的接口自动化框架详细教程 前段时间由于公司测试方向的转型,由原来的web页面功能测试转变成接口测试,之前大多都是手工进行,利用postman和jmeter进行的接口测试,后来,组内有人讲原先web自动化的测试框架移驾成接口的自动化框架,使用的是java语言,但对于一个学java,却在学python的我来说,觉得python比起java更简单些,所以,我决定自

python+requests接口自动化测试框架实例详解

前段时间由于公司测试方向的转型,由原来的web页面功能测试转变成接口测试,之前大多都是手工进行,利用postman和jmeter进行的接口测试,后来,组内有人讲原先web自动化的测试框架移驾成接口的自动化框架,使用的是java语言,但对于一个学java,却在学python的我来说,觉得python比起java更简单些,所以,我决定自己写python的接口自动化测试框架,由于本人也是刚学习python,这套自动化框架目前已经基本完成了,于是进行一些总结,便于以后回顾温习,有许多不完善的地方,也遇到

类与接口的区别和详解

在C#中类和接口是非常重要的知识点.这里主要介绍这两种的类型. 1. 类 类的分类有:抽象类(abstract).密封类(sealed).静态类(static) 1.1 抽象类 关键字: abstract使用目的:若所有子类拥有共同的特性,可以把这个特性放到一个抽象类中,子类继承此抽象类. 特点: 1.不能被实例化:ClassName en=new ClassName();//这样会报错. 2.抽象成员必须包含在抽象类中. 3.抽象类除了抽象成员外,还可以包含别的成员(不用关键字 abstrac