除夕夜,当然也不能忘记了敲代码,今天来分享一下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方法也是相同的道理。
所以我们可以知道有时抛出并发异常并不是由于多线程并发造成的,而是由于计数器的不一致
只有永不停歇的前进,才能保证不会后退