Collection的父类Iterable

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两次

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值