1.Iterator
使用实例:
List<String> strings = new ArrayList<>();
strings.add("A");
strings.add("B");
strings.add("C");
strings.add("D");
strings.add("E");
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()){
String next = iterator.next();
if (next.equals("A")){
iterator.remove();
}
System.out.println(next + " " + strings.size());
}
-
所有 Collection 的子类都有 iterator() 方法来获得 Iterator,通过 Iterator 的标准操作方法,可以让我们不必关心具体集合的类型,从而避免向客户端暴露出集合的内部结构。
-
在使用 Iterator iterator = strings.iterator() 生成迭代器后不能通过集合的方法改变集合的大小
ArrayList内部类实现迭代器源码:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount; //此处将list的size传入
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);//调用的是lsit的方法
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount; //重新传入list的size
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
f (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}