基于jdk 1.8.0_91?的源碼解析
public class WeakHashMap
extends AbstractMap
implements Map {
/**
* 默認的初始容量是16,必須是2的冪
*/
? ? private static final int DEFAULT_INITIAL_CAPACITY =16;
/**
* 最大容量(必須是2的冪且小于2的30次方,傳入容量過大將被這個值替換)
*/
? ? private static final int MAXIMUM_CAPACITY =1 <<30;
/**
* 默認加載因子
*/
? ? private static final float DEFAULT_LOAD_FACTOR =0.75f;
/**
* 存儲數據的Entry數組,長度是2的冪。
* WeakHashMap是采用拉鏈法實現的,每一個Entry本質上是一個單向鏈表
*/
? ? Entry[]table;
/**
* 表示WeakHashMap的大小
*/
? ? private int size;
/**
* WeakHashMap的閾值,用于判斷是否需要調整WeakHashMap的容量(threshold = 容量*加載因子)
*/
? ? private int threshold;
/**
* 加載因子實際大小
*/
? ? private final float loadFactor;
/**
*? queue保存的是“已被GC清除”的“弱引用的鍵”。
* 弱引用和ReferenceQueue 是聯合使用的:如果弱引用所引用的對象被垃圾回收,Java虛擬機就會把這個弱引用加入到與之關聯的引用隊列中
*/
? ? private final ReferenceQueuequeue =new ReferenceQueue<>();
/**
* WeakHashMap被改變的次數
*/
? ? int modCount;
@SuppressWarnings("unchecked")
private Entry[] newTable(int n) {
return (Entry[])new Entry[n];
}
/**
*? 定義包含“容量大小”和“加載因子”的構造函數
*/
? ? public WeakHashMap(int initialCapacity,float loadFactor) {
// 如果容量大小小于0 ,就拋出參數不合法異常
? ? ? ? if (initialCapacity <0)
throw new IllegalArgumentException("Illegal Initial Capacity: "+
initialCapacity);
// 如果容量大小>最大容量 ,就讓WeakHashMap的最大容量只能是MAXIMUM_CAPACITY
? ? ? ? if (initialCapacity >MAXIMUM_CAPACITY)
initialCapacity =MAXIMUM_CAPACITY;
// 如果加載因子<=0? 或者 加載因子沒有 數字 就拋出參數不合法異常
? ? ? ? if (loadFactor <=0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load factor: "+
loadFactor);
// 找出“大于initialCapacity”的最小的2的冪
? ? ? ? int capacity =1;
while (capacity < initialCapacity)
//? capacity<< n 等效于 capacity 乘以 2的 N 次方
? ? ? ? ? ? capacity <<=1;
// 創建Entry數組,用來保存數據
? ? ? ? table = newTable(capacity);
// 設置“加載因子”
? ? ? ? this.loadFactor = loadFactor;
// 設置“WeakHashMap閾值”,當WeakHashMap中存儲數據的數量達到threshold時,就需要將WeakHashMap的容量加倍。
? ? ? ? threshold = (int)(capacity * loadFactor);
}
/**
*? 創建指定“容量大小”的構造函數
*/
? ? public WeakHashMap(int initialCapacity) {
this(initialCapacity,DEFAULT_LOAD_FACTOR);
}
/**
*? 創建默認構造函數
*/
? ? public WeakHashMap() {
this(DEFAULT_INITIAL_CAPACITY,DEFAULT_LOAD_FACTOR);
}
/**
* 創建包含“子Map”的構造函數
*/
? ? public WeakHashMap(Map m) {
this(Math.max((int) (m.size() /DEFAULT_LOAD_FACTOR) +1,
DEFAULT_INITIAL_CAPACITY),
DEFAULT_LOAD_FACTOR);
// 將m中的全部元素逐個添加到WeakHashMap中
? ? ? ? putAll(m);
}
// internal utilities
/**
* 鍵為null的mask值。
* 因為WeakReference中允許“null的key”,若直接插入“null的key”,將其當作弱引用時,會被刪除。
* 因此,這里對于“key為null”的清空,都統一替換為“key為NULL_KEY”,“NULL_KEY”是“靜態的final常量”。
*/
? ? private static final ObjectNULL_KEY =new Object();
/**
* 對“null的key”進行特殊處理
*/
? ? private static Object maskNull(Object key) {
return (key ==null) ?NULL_KEY : key;
}
/**
* 還原對“null的key”的特殊處理
*/
? ? static Object unmaskNull(Object key) {
return (key ==NULL_KEY) ?null : key;
}
/**
*? 判斷“x”和“y”是否相等
*/
? ? private static boolean eq(Object x, Object y) {
return x == y || x.equals(y);
}
/**
* 返回索引值
* h & (length-1)保證返回值的小于length
*/
? ? final int hash(Object k) {
int h = k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
? ? ? ? h ^= (h >>>20) ^ (h >>>12);
return h ^ (h >>>7) ^ (h >>>4);
}
/**
* 返回哈希代碼h 的索引
*/
? ? private static int indexFor(int h,int length) {
return h & (length-1);
}
/**
*? 清空table中無用鍵值對。原理如下:
*(當WeakHashMap中某個“弱引用的key”由于沒有再被引用而被GC收回時,
*? 被回收的“該弱引用key”也被會被添加到"ReferenceQueue(queue)"中。
*? 當我們執行expungeStaleEntries時,
*? 就遍歷"ReferenceQueue(queue)"中的所有key
*? 然后就在“WeakReference的table”中刪除與“ReferenceQueue(queue)中key”對應的鍵值對
*/
? ? private void expungeStaleEntries() {
for (Object x; (x =queue.poll()) !=null; ) {
synchronized (queue) {
@SuppressWarnings("unchecked")
Entry e = (Entry) x;
int i =indexFor(e.hash,table.length);
Entry prev =table[i];
Entry p = prev;
while (p !=null) {
Entry next = p.next;
if (p == e) {
if (prev == e)
table[i] = next;
else
? ? ? ? ? ? ? ? ? ? ? ? ? ? prev.next = next;
// Must not null out e.next;
// stale entries may be in use by a HashIterator
? ? ? ? ? ? ? ? ? ? ? ? e.value =null;// Help GC
? ? ? ? ? ? ? ? ? ? ? ? size--;
break;
}
prev = p;
p = next;
}
}
}
}
/**
* 獲取WeakHashMap的table(存放鍵值對的數組)
*/
? ? private Entry[] getTable() {
expungeStaleEntries();
return table;
}
/**
*? 獲取WeakHashMap的實際大小
*/
? ? public int size() {
if (size ==0)
return 0;
expungeStaleEntries();
return size;
}
/**
* 判斷是否為空
*/
? ? public boolean isEmpty() {
return size() ==0;
}
/**
*? 獲取key對應的value
*/
? ? public V get(Object key) {
//進一步判斷value是否為空
? ? ? ? Object k =maskNull(key);
int h = hash(k);
Entry[] tab = getTable();
int index =indexFor(h, tab.length);
Entry e = tab[index];
// 在“該hash值對應的鏈表”上查找“鍵值等于key”的元素
? ? ? ? while (e !=null) {
if (e.hash == h &&eq(k, e.get()))
return e.value;
e = e.next;
}
return null;
}
/**
* WeakHashMap是否包含key
*/
? ? public boolean containsKey(Object key) {
return getEntry(key) !=null;
}
/**
* 返回“鍵為key”的鍵值對
*/
? ? Entry getEntry(Object key) {
Object k =maskNull(key);
int h = hash(k);
Entry[] tab = getTable();
int index =indexFor(h, tab.length);
Entry e = tab[index];
while (e !=null && !(e.hash == h &&eq(k, e.get())))
e = e.next;
return e;
}
/**
*? 將“key-value”添加到WeakHashMap中
*/
? ? public V put(K key,V value) {
Object k =maskNull(key);
int h = hash(k);
Entry[] tab = getTable();
int i =indexFor(h, tab.length);
// 若“該key”對應的鍵值對已經存在,則用新的value取代舊的value。然后退出!
? ? ? ? for (Entry e = tab[i]; e !=null; e = e.next) {
if (h == e.hash &&eq(k, e.get())) {
V oldValue = e.value;
if (value != oldValue)
e.value = value;
return oldValue;
}
}
// 若“該key”對應的鍵值對不存在于WeakHashMap中,則將“key-value”添加到table中
? ? ? ? modCount++;
Entry e = tab[i];
tab[i] =new Entry<>(k, value,queue, h, e);
if (++size >=threshold)
resize(tab.length *2);
return null;
}
/**
* 重新調整WeakHashMap的大小,newCapacity是調整后的單位
*/
? ? void resize(int newCapacity) {
Entry[] oldTable = getTable();
int oldCapacity = oldTable.length;
if (oldCapacity ==MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
// 新建一個newTable,將“舊的table”的全部元素添加到“新的newTable”中,
// 然后,將“新的newTable”賦值給“舊的table”。
? ? ? ? Entry[] newTable = newTable(newCapacity);
transfer(oldTable, newTable);
table = newTable;
if (size >=threshold /2) {
threshold = (int)(newCapacity *loadFactor);
}else {
// 刪除table中“已被GC回收的key對應的鍵值對”
? ? ? ? ? ? expungeStaleEntries();
transfer(newTable, oldTable);
table = oldTable;
}
}
/**
* 將WeakHashMap中的全部元素都添加到newTable中
*/
? ? private void transfer(Entry[] src, Entry[] dest) {
for (int j =0; j < src.length; ++j) {
Entry e = src[j];
src[j] =null;
while (e !=null) {
Entry next = e.next;
Object key = e.get();
if (key ==null) {
e.next =null;// Help GC
? ? ? ? ? ? ? ? ? ? e.value =null;//? "? "
? ? ? ? ? ? ? ? ? ? size--;
}else {
int i =indexFor(e.hash, dest.length);
e.next = dest[i];
dest[i] = e;
}
e = next;
}
}
}
/**
*? 將"m"的全部元素都添加到WeakHashMap中
*/
? ? public void putAll(Map m) {
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded ==0)
return;
/**
*? 計算容量是否足夠,
*? 若“當前實際容量 < 需要的容量”,則將容量x2
*/
? ? ? ? if (numKeysToBeAdded >threshold) {
int targetCapacity = (int)(numKeysToBeAdded /loadFactor +1);
if (targetCapacity >MAXIMUM_CAPACITY)
targetCapacity =MAXIMUM_CAPACITY;
int newCapacity =table.length;
while (newCapacity < targetCapacity)
newCapacity <<=1;
if (newCapacity >table.length)
resize(newCapacity);
}
// 將“m”中的元素逐個添加到WeakHashMap中。
? ? ? ? for (Map.Entry e : m.entrySet())
put(e.getKey(), e.getValue());
}
/**
*? 移除“鍵為key”元素
*/
? ? public V remove(Object key) {
Object k =maskNull(key);
int h = hash(k);
Entry[] tab = getTable();
int i =indexFor(h, tab.length);
Entry prev = tab[i];
Entry e = prev;
// 刪除鏈表中“鍵為key”的元素
? ? ? ? while (e !=null) {
Entry next = e.next;
if (h == e.hash &&eq(k, e.get())) {
modCount++;
size--;
if (prev == e)
tab[i] = next;
else
? ? ? ? ? ? ? ? ? ? prev.next = next;
return e.value;
}
prev = e;
e = next;
}
return null;
}
/**
*? 移除“鍵值對”
* */
? ? boolean removeMapping(Object o) {
if (!(oinstanceof Map.Entry))
return false;
Entry[] tab = getTable();
Map.Entry entry = (Map.Entry)o;
Object k =maskNull(entry.getKey());
int h = hash(k);
int i =indexFor(h, tab.length);
Entry prev = tab[i];
Entry e = prev;
while (e !=null) {
Entry next = e.next;
if (h == e.hash && e.equals(entry)) {
modCount++;
size--;
if (prev == e)
tab[i] = next;
else
? ? ? ? ? ? ? ? ? ? prev.next = next;
return true;
}
prev = e;
e = next;
}
return false;
}
/**
* 清空WeakHashMap,將所有的元素設為null
*/
? ? public void clear() {
while (queue.poll() !=null)
;
modCount++;
Arrays.fill(table,null);
size =0;
while (queue.poll() !=null)
;
}
/**
* 是否包含“值為value”的元素
*/
? ? public boolean containsValue(Object value) {
if (value==null)
return containsNullValue();
Entry[] tab = getTable();
for (int i = tab.length; i-- >0;)
for (Entry e = tab[i]; e !=null; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
/**
* 判斷是否包含null值
*/
? ? private boolean containsNullValue() {
Entry[] tab = getTable();
for (int i = tab.length; i-- >0;)
for (Entry e = tab[i]; e !=null; e = e.next)
if (e.value==null)
return true;
return false;
}
/**
* Entry是單向鏈表。
* 它是 “WeakHashMap鏈式存儲法”對應的鏈表。
* 它實現了Map.Entry 接口,即實現getKey(), getValue(), setValue(V value), equals(Object o), hashCode()這些函數.
*/
? ? private static class Entryextends WeakReferenceimplements Map.Entry {
V value;
final int hash;
// 指向下一個節點
? ? ? ? Entrynext;
/**
* 創建下一個節點
*/
? ? ? ? Entry(Object key,V value,
ReferenceQueue queue,
int hash, Entry next) {
super(key, queue);
this.value = value;
this.hash? = hash;
this.next? = next;
}
@SuppressWarnings("unchecked")
public K getKey() {
return (K) WeakHashMap.unmaskNull(get());
}
public V getValue() {
return value;
}
/**
* 設置新的值
*/
? ? ? ? public V setValue(V newValue) {
V oldValue =value;
value = newValue;
return oldValue;
}
/**
*? 判斷兩個Entry是否相等
*/
? ? ? ? public boolean equals(Object o) {
if (!(oinstanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
K k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 !=null && k1.equals(k2))) {
V v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 !=null && v1.equals(v2)))
return true;
}
return false;
}
/**
* 實現hashCode()
*/
? ? ? ? public int hashCode() {
K k = getKey();
V v = getValue();
return Objects.hashCode(k) ^ Objects.hashCode(v);
}
public String toString() {
return getKey() +"=" + getValue();
}
}
/**
* HashIterator是WeakHashMap迭代器的抽象出來的父類,實現了公共了函數。
*/
? ? private abstract class HashIteratorimplements Iterator {
private int index;
private Entryentry;
private EntrylastReturned;
private int expectedModCount =modCount;
private ObjectnextKey;
private ObjectcurrentKey;
HashIterator() {
index = isEmpty() ?0 :table.length;
}
public boolean hasNext() {
Entry[] t =table;
while (nextKey ==null) {
Entry e =entry;
int i =index;
while (e ==null && i >0)
e = t[--i];
entry = e;
index = i;
if (e ==null) {
currentKey =null;
return false;
}
nextKey = e.get();// hold on to key in strong ref
? ? ? ? ? ? ? ? if (nextKey ==null)
entry =entry.next;
}
return true;
}
/**
* 獲取下一個元素
*/
? ? ? ? protected Entry nextEntry() {
if (modCount !=expectedModCount)
throw new ConcurrentModificationException();
if (nextKey ==null && !hasNext())
throw new NoSuchElementException();
lastReturned =entry;
entry =entry.next;
currentKey =nextKey;
nextKey =null;
return lastReturned;
}
/**
* 刪除當前元素
*/
? ? ? ? public void remove() {
if (lastReturned ==null)
throw new IllegalStateException();
if (modCount !=expectedModCount)
throw new ConcurrentModificationException();
WeakHashMap.this.remove(currentKey);
expectedModCount =modCount;
lastReturned =null;
currentKey =null;
}
}
/**
* value的迭代器
*/
? ? private class ValueIteratorextends HashIterator {
public V next() {
return nextEntry().value;
}
}
/**
* key的迭代器
*/
? ? private class KeyIteratorextends HashIterator {
public K next() {
return nextEntry().getKey();
}
}
/**
* Entry的迭代器
*/
? ? private class EntryIteratorextends HashIterator> {
public Map.Entry next() {
return nextEntry();
}
}
/**
* WeakHashMap的Entry對應的集合
*/
? ? private transient Set>entrySet;
/**
* 返回“key的集合”,實際上返回一個“KeySet對象”
*/
? ? public Set keySet() {
Set ks =keySet;
return (ks !=null ? ks : (keySet =new KeySet()));
}
//KeySet繼承于AbstractSet,說明該集合中沒有重復的Key。
? ? private class KeySetextends AbstractSet {
public Iterator iterator() {
return new KeyIterator();
}
public int size() {
return WeakHashMap.this.size();
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
if (containsKey(o)) {
WeakHashMap.this.remove(o);
return true;
}
else
? ? ? ? ? ? ? ? return false;
}
public void clear() {
WeakHashMap.this.clear();
}
public Spliterator spliterator() {
return new KeySpliterator<>(WeakHashMap.this,0, -1,0,0);
}
}
/**
* 返回“value集合”,實際上返回的是一個Values對象
*/
? ? public Collection values() {
Collection vs =values;
return (vs !=null) ? vs : (values =new Values());
}
private class Valuesextends AbstractCollection {
public Iterator iterator() {
return new ValueIterator();
}
public int size() {
return WeakHashMap.this.size();
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
WeakHashMap.this.clear();
}
public Spliterator spliterator() {
return new ValueSpliterator<>(WeakHashMap.this,0, -1,0,0);
}
}
/**
*? Values中的元素能夠重復。因為不同的key可以指向相同的value。
*/
? ? public Set> entrySet() {
Set> es =entrySet;
return es !=null ? es : (entrySet =new EntrySet());
}
/**
*? EntrySet繼承于AbstractSet,說明該集合中沒有重復的EntrySet。
*/
? ? private class EntrySetextends AbstractSet> {
public Iterator> iterator() {
return new EntryIterator();
}
public boolean contains(Object o) {
if (!(oinstanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Entry candidate = getEntry(e.getKey());
return candidate !=null && candidate.equals(e);
}
public boolean remove(Object o) {
return removeMapping(o);
}
public int size() {
return WeakHashMap.this.size();
}
public void clear() {
WeakHashMap.this.clear();
}
private List> deepCopy() {
List> list =new ArrayList<>(size());
for (Map.Entry e :this)
list.add(new AbstractMap.SimpleEntry<>(e));
return list;
}
public Object[] toArray() {
return deepCopy().toArray();
}
public T[] toArray(T[] a) {
return deepCopy().toArray(a);
}
public Spliterator> spliterator() {
return new EntrySpliterator<>(WeakHashMap.this,0, -1,0,0);
}
}
/**
* 進行遍歷的集合元素
*/
? ? @SuppressWarnings("unchecked")
@Override
? ? public void forEach(BiConsumer action) {
Objects.requireNonNull(action);
int expectedModCount =modCount;
Entry[] tab = getTable();
for (Entry entry : tab) {
while (entry !=null) {
Object key = entry.get();
if (key !=null) {
action.accept((K)WeakHashMap.unmaskNull(key), entry.value);
}
entry = entry.next;
if (expectedModCount !=modCount) {
throw new ConcurrentModificationException();
}
}
}
}
/**
* 替換所有元素
*/
? ? @SuppressWarnings("unchecked")
@Override
? ? public void replaceAll(BiFunction function) {
Objects.requireNonNull(function);
int expectedModCount =modCount;
Entry[] tab = getTable();;
for (Entry entry : tab) {
while (entry !=null) {
Object key = entry.get();
if (key !=null) {
entry.value = function.apply((K)WeakHashMap.unmaskNull(key), entry.value);
}
entry = entry.next;
if (expectedModCount !=modCount) {
throw new ConcurrentModificationException();
}
}
}
}
/**
* 創建一個WeakHashMapSpliterator的靜態類
*/
? ? static class WeakHashMapSpliterator {
final WeakHashMapmap;
WeakHashMap.Entrycurrent;
int index;
int fence;
int est;
int expectedModCount;
WeakHashMapSpliterator(WeakHashMap m,int origin,
int fence,int est,
int expectedModCount) {
this.map = m;
this.index = origin;
this.fence = fence;
this.est = est;
this.expectedModCount = expectedModCount;
}
/**
* 在第一次使用時初始化圍欄和大小
*/
? ? ? ? final int getFence() {
int hi;
if ((hi =fence) <0) {
WeakHashMap m =map;
est = m.size();
expectedModCount = m.modCount;
hi =fence = m.table.length;
}
return hi;
}
/**
* 估計集合大小
*/
? ? ? ? public final long estimateSize() {
getFence();
return (long)est;
}
}
/**
* KeySpliteratord 的靜態類
*/
? ? static final class KeySpliterator
extends WeakHashMapSpliterator
implements Spliterator {
KeySpliterator(WeakHashMap m,int origin,int fence,int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
/**
* trySplit:ArrayListSpliterator的trySplit采用二分法,將前一半數據返回,
* 如果數據太小不能分了,返回null。而ConcurrentLinkedQueue和ConcurrentLinkedDeque的相應的Spliterator處理稍微復雜一點,
* 第一次取一個,第二個取兩個,不超過MAX_BATCH
* 對當前迭代器進行分割
*/
? ? ? ? public KeySpliterator trySplit() {
// 這里的分割方法只是把當前迭代器的開始索引和最后索引除以二而已
? ? ? ? ? ? int hi = getFence(), lo =index, mid = (lo + hi) >>>1;
// 需要遍歷的元素個數 est 也需要除以二喇~
? ? ? ? ? ? return (lo >= mid) ?null :
new KeySpliterator(map, lo,index = mid,est >>>=1,
expectedModCount);
}
/**
*? 在當前迭代器遍歷范圍遍歷一遍
*/
? ? ? ? public void forEachRemaining(Consumer action) {
int i, hi, mc;
if (action ==null)
throw new NullPointerException();
WeakHashMap m =map;
WeakHashMap.Entry[] tab = m.table;
if ((hi =fence) <0) {
mc =expectedModCount = m.modCount;
hi =fence = tab.length;
}
else
? ? ? ? ? ? ? ? mc =expectedModCount;
if (tab.length >= hi && (i =index) >=0 &&
(i < (index = hi) ||current !=null)) {
WeakHashMap.Entry p =current;
current =null;// exhaust
? ? ? ? ? ? ? ? do {
if (p ==null)
p = tab[i++];
else {
Object x = p.get();
p = p.next;
if (x !=null) {
@SuppressWarnings("unchecked")K k =
(K) WeakHashMap.unmaskNull(x);
action.accept(k);
}
}
}while (p !=null || i < hi);
}
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
/**
* 會遍歷迭代器遍歷的范圍之內的元素,當找到第一個非空元素的時候就會停止遍歷
*/
? ? ? ? public boolean tryAdvance(Consumer action) {
int hi;
if (action ==null)
throw new NullPointerException();
WeakHashMap.Entry[] tab =map.table;
if (tab.length >= (hi = getFence()) &&index >=0) {
while (current !=null ||index < hi) {
if (current ==null)
current = tab[index++];
else {
Object x =current.get();
current =current.next;
if (x !=null) {
@SuppressWarnings("unchecked")K k =
(K) WeakHashMap.unmaskNull(x);
action.accept(k);
if (map.modCount !=expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
}
return false;
}
public int characteristics() {
return Spliterator.DISTINCT;
}
}
/**
* 創建vaule迭代器
*/
? ? static final class ValueSpliterator
extends WeakHashMapSpliterator
implements Spliterator {
ValueSpliterator(WeakHashMap m,int origin,int fence,int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
/**
* 對當前迭代器進行分割
*/
? ? ? ? public ValueSpliterator trySplit() {
int hi = getFence(), lo =index, mid = (lo + hi) >>>1;
return (lo >= mid) ?null :
new ValueSpliterator(map, lo,index = mid,est >>>=1,
expectedModCount);
}
/**
*? 在當前迭代器遍歷范圍遍歷一遍
*/
? ? ? ? public void forEachRemaining(Consumer action) {
int i, hi, mc;
if (action ==null)
throw new NullPointerException();
WeakHashMap m =map;
WeakHashMap.Entry[] tab = m.table;
if ((hi =fence) <0) {
mc =expectedModCount = m.modCount;
hi =fence = tab.length;
}
else
? ? ? ? ? ? ? ? mc =expectedModCount;
if (tab.length >= hi && (i =index) >=0 &&
(i < (index = hi) ||current !=null)) {
WeakHashMap.Entry p =current;
current =null;//排出
? ? ? ? ? ? ? ? do {
if (p ==null)
p = tab[i++];
else {
Object x = p.get();
V v = p.value;
p = p.next;
if (x !=null)
action.accept(v);
}
}while (p !=null || i < hi);
}
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
/**
* 會遍歷迭代器遍歷的范圍之內的元素,當找到第一個非空元素的時候就會停止遍歷
*/
? ? ? ? public boolean tryAdvance(Consumer action) {
int hi;
if (action ==null)
throw new NullPointerException();
WeakHashMap.Entry[] tab =map.table;
if (tab.length >= (hi = getFence()) &&index >=0) {
while (current !=null ||index < hi) {
if (current ==null)
current = tab[index++];
else {
Object x =current.get();
V v =current.value;
current =current.next;
if (x !=null) {
action.accept(v);
if (map.modCount !=expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
}
return false;
}
public int characteristics() {
return 0;
}
}
/**
* 創建一個EntrySpliterator迭代器
*/
? ? static final class EntrySpliterator
extends WeakHashMapSpliterator
implements Spliterator> {
EntrySpliterator(WeakHashMap m,int origin,int fence,int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
/**
* 對當前迭代器進行分割
*/
? ? ? ? public EntrySpliterator trySplit() {
int hi = getFence(), lo =index, mid = (lo + hi) >>>1;
return (lo >= mid) ?null :
new EntrySpliterator(map, lo,index = mid,est >>>=1,
expectedModCount);
}
/**
*? 在當前迭代器遍歷范圍遍歷一遍
*/
? ? ? ? public void forEachRemaining(Consumer> action) {
int i, hi, mc;
if (action ==null)
throw new NullPointerException();
WeakHashMap m =map;
WeakHashMap.Entry[] tab = m.table;
if ((hi =fence) <0) {
mc =expectedModCount = m.modCount;
hi =fence = tab.length;
}
else
? ? ? ? ? ? ? ? mc =expectedModCount;
if (tab.length >= hi && (i =index) >=0 &&
(i < (index = hi) ||current !=null)) {
WeakHashMap.Entry p =current;
current =null;// exhaust
? ? ? ? ? ? ? ? do {
if (p ==null)
p = tab[i++];
else {
Object x = p.get();
V v = p.value;
p = p.next;
if (x !=null) {
@SuppressWarnings("unchecked")K k =
(K) WeakHashMap.unmaskNull(x);
action.accept
(new AbstractMap.SimpleImmutableEntry(k, v));
}
}
}while (p !=null || i < hi);
}
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
/**
* 會遍歷迭代器遍歷的范圍之內的元素,當找到第一個非空元素的時候就會停止遍歷
*/
? ? ? ? public boolean tryAdvance(Consumer> action) {
int hi;
if (action ==null)
throw new NullPointerException();
WeakHashMap.Entry[] tab =map.table;
if (tab.length >= (hi = getFence()) &&index >=0) {
while (current !=null ||index < hi) {
if (current ==null)
current = tab[index++];
else {
Object x =current.get();
V v =current.value;
current =current.next;
if (x !=null) {
@SuppressWarnings("unchecked")K k =
(K) WeakHashMap.unmaskNull(x);
action.accept
(new AbstractMap.SimpleImmutableEntry(k, v));
if (map.modCount !=expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
}
return false;
}
/**
* Spliterator的參數
*/
? ? ? ? public int characteristics() {
return Spliterator.DISTINCT;
}
}
}