迭代器模式在开源代码中的应用

迭代器模式的作用:提供一种方法来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。

案例

迭代器模式最经典的应用就是 JDK 中工具类 Iterator 接口的设计,定义了对集合的访问方法。

public interface Iterator<E> {

	boolean hasNext();

	E next();

	default void remove() {
		throw new UnsupportedOperationException("remove");
	}

	default void forEachRemaining(Consumer<? super E> action) {
		Objects.requireNonNull(action);
		while (hasNext())
			action.accept(next());
	}
}

每种集合中都有 iterator() 方法,返回各自的迭代器,迭代器按照各自算法实现了 Iterator 接口,满足遍历需求。

如 ArrayLis 中

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {

	public Iterator<E> iterator() {
		return new Itr();
	}

	//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;

		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);
				cursor = lastRet;
				lastRet = -1;
				expectedModCount = modCount;
			} catch (IndexOutOfBoundsException ex) {
				throw new ConcurrentModificationException();
			}
		}

		@Override
		@SuppressWarnings("unchecked")
		public void forEachRemaining(Consumer<? super E> consumer) {
			Objects.requireNonNull(consumer);
			final int size = ArrayList.this.size;
			int i = cursor;
			if (i >= size) {
				return;
			}
			final Object[] elementData = ArrayList.this.elementData;
			if (i >= elementData.length) {
				throw new ConcurrentModificationException();
			}
			while (i != size && modCount == expectedModCount) {
				consumer.accept((E) elementData[i++]);
			}
			// update once at end of iteration to reduce heap write traffic
			cursor = i;
			lastRet = i - 1;
			checkForComodification();
		}

		final void checkForComodification() {
			if (modCount != expectedModCount)
				throw new ConcurrentModificationException();
		}
	}

}

HashSet 中

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable {
	
	// HashSet 是基于 HashMap 实现,直接返回 key 的 Set 的 Iterator
	public Iterator<E> iterator() {
		return map.keySet().iterator();
	}
	
}

队列 PriorityQueue 中

public class PriorityQueue<E> extends AbstractQueue<E> implements java.io.Serializable {
	public Iterator<E> iterator() {
		return new Itr();
	}
	
	//内部对 Iterator 接口进行实现,迭代 PriorityQueue
	private final class Itr implements Iterator<E> {
		private int cursor = 0;

		private int lastRet = -1;

		private ArrayDeque<E> forgetMeNot = null;

		private E lastRetElt = null;

		private int expectedModCount = modCount;

		public boolean hasNext() {
			return cursor < size ||
				(forgetMeNot != null && !forgetMeNot.isEmpty());
		}

		@SuppressWarnings("unchecked")
		public E next() {
			if (expectedModCount != modCount)
				throw new ConcurrentModificationException();
			if (cursor < size)
				return (E) queue[lastRet = cursor++];
			if (forgetMeNot != null) {
				lastRet = -1;
				lastRetElt = forgetMeNot.poll();
				if (lastRetElt != null)
					return lastRetElt;
			}
			throw new NoSuchElementException();
		}

		public void remove() {
			if (expectedModCount != modCount)
				throw new ConcurrentModificationException();
			if (lastRet != -1) {
				E moved = PriorityQueue.this.removeAt(lastRet);
				lastRet = -1;
				if (moved == null)
					cursor--;
				else {
					if (forgetMeNot == null)
						forgetMeNot = new ArrayDeque<>();
					forgetMeNot.add(moved);
				}
			} else if (lastRetElt != null) {
				PriorityQueue.this.removeEq(lastRetElt);
				lastRetElt = null;
			} else {
				throw new IllegalStateException();
			}
			expectedModCount = modCount;
		}
	}
}

【Java学习资源】整理推荐


【Java面试题与答案】整理推荐

猜你喜欢

转载自blog.csdn.net/meism5/article/details/108504973