设计模式--迭代器模式
1 概述
由于迭代器模式实在太常见了,所以自己就简单写一下就好。
1.1 定义
迭代器模式(Iterator Design)提供一种方法顺序访问容器中的各个元素,而又不暴露其内部具体的实现。
1.2 应用
JDK中的java.util包所有Collection集合都实现了Iterable接口,该接口有一个方法返回Iterator对象。
JDK中foreach语法内部就是迭代器原理。
2 详解
JDK中Iterable接口,该接口会返回一个Iterator对象。
1 public interface Iterable<T> { 2 Iterator<T> iterator(); 3 } 4 5 public interface Iterator<E> { 6 boolean hasNext(); 7 8 E next(); 9 10 default void remove() { 11 throw new UnsupportedOperationException("remove"); 12 } 13 14 default void forEachRemaining(Consumer<? super E> action) { 15 Objects.requireNonNull(action); 16 while (hasNext()) 17 action.accept(next()); 18 } 19 }
JDK中Collection接口
1 public interface Collection<E> extends Iterable<E> { 2 Iterator<E> iterator(); 3 }
JDK中ArrayList类
1 public class ArrayList<E> extends AbstractList<E> 2 implements List<E>, RandomAccess, Cloneable, java.io.Serializable { 3 4 @Override 5 public Iterator<E> iterator() { 6 return new Itr(); 7 } 8 9 private class Itr implements Iterator<E> { 10 int cursor; // index of next element to return 11 int lastRet = -1; // index of last element returned; -1 if no such 12 int expectedModCount = modCount; 13 14 public boolean hasNext() { 15 return cursor != size; 16 } 17 18 @SuppressWarnings("unchecked") 19 public E next() { 20 checkForComodification(); 21 int i = cursor; 22 if (i >= size) 23 throw new NoSuchElementException(); 24 Object[] elementData = ArrayList.this.elementData; 25 if (i >= elementData.length) 26 throw new ConcurrentModificationException(); 27 cursor = i + 1; 28 return (E) elementData[lastRet = i]; 29 } 30 31 public void remove() { 32 if (lastRet < 0) 33 throw new IllegalStateException(); 34 checkForComodification(); 35 36 try { 37 ArrayList.this.remove(lastRet); 38 cursor = lastRet; 39 lastRet = -1; 40 expectedModCount = modCount; 41 } catch (IndexOutOfBoundsException ex) { 42 throw new ConcurrentModificationException(); 43 } 44 } 45 46 @Override 47 @SuppressWarnings("unchecked") 48 public void forEachRemaining(Consumer<? super E> consumer) { 49 Objects.requireNonNull(consumer); 50 final int size = ArrayList.this.size; 51 int i = cursor; 52 if (i >= size) { 53 return; 54 } 55 final Object[] elementData = ArrayList.this.elementData; 56 if (i >= elementData.length) { 57 throw new ConcurrentModificationException(); 58 } 59 while (i != size && modCount == expectedModCount) { 60 consumer.accept((E) elementData[i++]); 61 } 62 // update once at end of iteration to reduce heap write traffic 63 cursor = i; 64 lastRet = i - 1; 65 checkForComodification(); 66 } 67 68 final void checkForComodification() { 69 if (modCount != expectedModCount) 70 throw new ConcurrentModificationException(); 71 } 72 } 73 74 }