Collection的父类Iterable

原创 2016年08月29日 15:17:50

Collection类继承自Iterable

public interface Collection<E> extends Iterable<E>

Iterable源码

/**
 * Instances of classes that implement this interface can be used with
 * the enhanced for loop.
 * 实现该接口的类实例能够使用增强的for循环
 * @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();
}

增强的for循环是什么呢,其实大家都见过
测试代码

public class test {
    public static void main(String[] args) {
        List<User> list = new ArrayList<User>();
        list.add(new User("1","张三"));
        list.add(new User("2","李四"));
        list.add(new User("3","王五"));
        list.add(new User("4","丁八"));

        Iterator iter = list.iterator();
        while(iter.hasNext()) {
            User user = (User)iter.next();
            System.out.println(user.toString());
        }
    }
}
class User{
    public String id;
    public String name;
}

Iterator 源码

/**
 * An iterator over a sequence of objects, such as a collection.
 * iterator就是一串objects对象,正如一个集合
 * <p>If a collection has been changed since the iterator was created,
 * methods {@code next} and {@code hasNext()} may throw a {@code ConcurrentModificationException}.
 * 如果iterator在创建之后有了改变,调用next、hasNext方法则会抛出异常ConcurrentModificationException
 * It is not possible to guarantee that this mechanism works in all cases of unsynchronized(异步) concurrent(同时发生修改) modification.
 * 这一机制不能保证各种情况下的,异步线程并发修改 
 * It should only be used for debugging purposes. Iterators with this
 * behavior are called fail-fast iterators.
 * 它应该用于调试目的
 * <p>Implementing {@link Iterable} and returning an {@code Iterator} allows your
 * class to be used as a collection with the enhanced for loop.
 *
 * @param <E>
 *            the type of object returned by the iterator.
 */
public interface Iterator<E> {
    /**
     * Returns true if there is at least one more element, false otherwise.
     * true 至少有一个或多个元素
     * @see #next
     */
    public boolean hasNext();

    /**
     * Returns the next object and advances the iterator.
     *
     * @return the next object.
     * @throws NoSuchElementException
     *             if there are no more elements.
     * @see #hasNext
     */
    public E next();

    /**
     * Removes the last object returned by {@code next} from the collection.
     * This method can only be called once between each call to {@code next}.
     *
     * @throws UnsupportedOperationException
     *             if removing is not supported by the collection being
     *             iterated.
     * @throws IllegalStateException
     *             if {@code next} has not been called, or {@code remove} has
     *             already been called after the last call to {@code next}.
     */
    public void remove();
}

抛异常情况
1. ConcurrentModificationException
iterator被创建后,list又使用iterator期间又做了修改

List<User> list = new ArrayList<User>();
list.add(new User("1","张三"));
list.add(new User("2","李四"));
list.add(new User("3","王五"));
list.add(new User("4","丁八"));

Iterator iter = list.iterator();
while(iter.hasNext()) {
    User user = (User)iter.next();
    if(user.id.equals("2")){
        list.add(new User("5","黄石"));
    }
    System.out.println(user.toString());
}

异常信息

Exception in thread "main" User{id='1', name='张三'}
User{id='2', name='李四'}
java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at com.luomo.test.test.main(test.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

2.next方法抛出的NoSuchElementException

List<User> list = new ArrayList<User>();
Iterator iter = list.iterator();
while(!iter.hasNext()) {
    User user = (User)iter.next();
    System.out.println(user.toString());
}

List<User> list = new ArrayList<User>();
list.add(new User("1","张三"));
list.add(new User("2","李四"));
list.add(new User("3","王五"));
list.add(new User("4","丁八"));

Iterator iter = list.iterator();
while(iter.hasNext()) {
    User user = (User)iter.next();
    System.out.println(user.toString());
}
System.out.println(((User)iter.next()).toString());

异常信息

 Exception in thread "main" java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:854)
    at com.luomo.test.test.main(test.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

3.remove方法抛出的异常
UnsupportedOperationException
删除一个非当前的集合类,如list的子类都是User,如果你remove一个Employee类就会出现这个问题
IllegalStateException
1>iter.hasNext()==false时,remove
2>连着remove两次

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Hive On Spark报错:Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable

解决Hive On Spark 报错Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterab...

Core Java (二十) Iterator,Iterable,Collection接口

Java集合类库将集合的接口与实现分离。同样的接口,可以有不同的实现。 Java集合类的基本接口是Collection接口。而Collection接口必须实现Iterator接口。 以下图表示集合...

【Java编程】Foreach对数组、Collection对象、Iterable对象的遍历

1、foreach介绍及其使用范围 foreach语句是java5的新特征之一,在遍历数组、集合、Iterable对象方面,为开发人员提供了极大的方便。foreach语句是for语句特殊情况下的增强...

Java集合框架复习之Collection接口,iterator接口,iterable接口(二)

1.Collection接口中处理集合元素的方法 boolean add(E e) boolean addAll(Collection)  void clear() boolean conta...

java基础巩固系列(九):持有对象之间的使用与关系(Iterable、Collection、List、Queue、Set、Map、Stack)

java中的持有对象之间的继承关系

【Java编程】foreach支持集合、Collection、Iterable遍历原因分析

1、foreach循环支持对Iterable类(实现了Iterable接口)的遍历,该结论在本blog第3节得到论证; 2、Collection接口继承Iterable接口,foreach支持对实现了...

Iterator与Iterable之foreach循环输出自定义类

无意中在网上看到一篇文章,把作者的想法进行了实现并进行了改进。 原文地址http://my.oschina.net/u/1412027/blog/226376 原文内容:      从Java5起,...

父类的引用指向子类对象

Java的多态性           面向对象编程有三个特征,即封装、继承和多态。     封装隐藏了类的内部实现机制,从而可以在不影响使用者的前提下改变类的内部结构,同时保护了数据。 ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)