迭代器模式的作用:提供一種方法來順序訪問聚合物件中的一系列資料,而不暴露聚合物件的內部表示,
案例
迭代器模式最經典的應用就是 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面試題與答案】整理推薦
- 基礎與語法
- 集合
- 網路編程
- 并發編程
- Web
- 安全
- 設計模式
- 框架
- 演算法與資料結構
- 例外
- 檔案決議與生成
- Linux
- MySQL
- Oracle
- Redis
- Dubbo
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/12980.html
標籤:其他
上一篇:Python爬蟲入門教程 88-100 Web Scraper 不用一行代碼就能學會的爬蟲程式
下一篇:Redis分布式鎖的正確姿勢
