Iterator源码分析

除夕夜,当然也不能忘记了敲代码,今天来分享一下Iterator的一些小知识

Iterator的源码分析

// 判断是否还有下一个元素
boolean hasNext();
// 获取游标当前元素
E next();
// 删除游标当前元素
default void remove() {
        throw new UnsupportedOperationException("remove");
}
// 1.8中使用的遍历方法
default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
}

使用方法

demo:

@SuppressWarnings("unchecked")
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 3, 2, 4, 5));

        for(Iterator<Integer> it = list.iterator(); it.hasNext();) {
            Integer number = it.next();
            if (number % 2 == 0) {
                it.remove();
            }
        }
        System.out.println(list);
        list.add(2);
        list.add(4);
        Iterator iterator = list.iterator();
        iterator.forEachRemaining(o -> System.out.print(o + " "));
}

output:

[1, 3, 5]
1 3 5 2 4 

异常原因:

NoSuchElementException

当游标移动到末尾时,再调用next方法,就会报出这个异常,代表不存在元素

UnsupportedOperationException

有些方法没有对remove方法进行重写,所以会抛出默认的
throw new UnsupportedOperationException(“remove”);

NullPointerException

当传入的动作为空时会抛出这个异常

IllegalStateException

当调用remove之前没有调用next时会抛出这个异常

ConcurrentModificationException

并发异常,当modCount和expectedModCount不一致时,会抛出该异常,后面会详细介绍一下这个问题

Iterator和集合方法为什么不能一起使用?

首先来看一下下面这段代码

Set<Integer> set = new HashSet<>(Arrays.asList(1, 3, 2, 4, 5));
        Iterator<Integer> it = set.iterator();
        while (it.hasNext()) {
            Integer number= it.next();
            if (number % 2 == 0) {
                set.remove(number);
            }
}

这段代码抛出了ConcurrentModificationException的异常,由于Set的底层是由HashMap实现的,所以我们看一下源码来分析

public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
}
  • 这里我们看到了modCount和expectedModCount,modCount是记录HashMap的修改次数,而expectedModCount是HashIterator的修改次数,属于两个不同的计数器。

  • 当使用Iterator进行遍历的同时,调用set的remove方法时,会造成两个计数器不同步的现象,所以抛出了ConcurrentModificationException,当然add方法也是相同的道理。

  • 所以我们可以知道有时抛出并发异常并不是由于多线程并发造成的,而是由于计数器的不一致

只有永不停歇的前进,才能保证不会后退

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值