WeakhashMap源碼2

public class WeakHashMapIteratorTest {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        Map map = new WeakHashMap1(7);
        for (int i = 0; i < 3; i++) {
            map.put("k" + i, "v" + i);
        }
        // 經過entrySet()遍歷WeakHashMap的key-value
        iteratorHashMapByEntryset(map);
        // 經過keySet()遍歷WeakHashMap的key-value
        iteratorHashMapByKeyset(map);
        // 單單遍歷WeakHashMap的value
        iteratorHashMapJustValues(map);
    }

    // 經過entry set遍歷WeakHashMap
    @SuppressWarnings("rawtypes")
    private static void iteratorHashMapByEntryset(Map map) {
        if (map == null)
            return;
        String key = null;
        String integ = null;
        // entrySet()返回new EntrySet()這個對象。iterator()返回new EntryIterator()對象。
        Collection c = map.entrySet();//c = [k2=v2, k1=v1, k0=v0] ,有值了。c是EntrySet類型。
        Iterator iter = c.iterator();//遍歷時候仍是調用HashIterator的next和hasNext方法,不是調用Collection c的方法。
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            key = (String) entry.getKey();
            integ = (String) entry.getValue();
        }
        System.out.println("iteratorHashMapByEntryset--->>>size: " + map.size());
    }

    /*
     * 經過keyset來遍歷WeakHashMap
     */
    private static void iteratorHashMapByKeyset(Map map) {
        if (map == null)
            return;
        String key = null;
        String integ = null;
        Collection c = map.keySet();//[k2, k1, k0]。c是KeySet類型。
        Iterator iter = c.iterator();//遍歷時候仍是調用HashIterator的next和hasNext方法,不是調用Collection c的方法。
        while (iter.hasNext()) {
            key = (String) iter.next();
            integ = (String) map.get(key);
        }
        System.out.println("iteratorHashMapByKeyset--->>>size: " + map.size());
    }

    /*
     * 遍歷WeakHashMap的values
     */
    private static void iteratorHashMapJustValues(Map map) {
        if (map == null)
            return;
        String key = null;
        String integ = null;
        Collection c = map.values();//c是Values類型。
        Iterator iter = c.iterator();//遍歷時候仍是調用HashIterator的next和hasNext方法,不是調用Collection c的方法。
        System.out.println("iteratorHashMapJustValues--->>>size: " + map.size());
        while (iter.hasNext()) {
            key = (String) iter.next();
            integ = (String) map.get(key);
        }
    }
}
public class WeakHashMap1<K,V> extends AbstractMap1<K,V> implements Map<K,V> {//弱hashmap
    private static final int DEFAULT_INITIAL_CAPACITY = 16;//初始容量2的冪次方
    private static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量2^30
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;//加載因子
    Entry<K,V>[] table;//實際元素位置,桶
    private int size;//大小
    private int threshold;//閾值:threshold = 容量*加載因子
    private final float loadFactor;//加載因素
    private final ReferenceQueue<Object> queue = new ReferenceQueue<>();//Enter的key被回收,Entry進入queue隊列。弱鍵失效的時候會把Entry添加到這個隊列中。
    int modCount;// WeakHashMap被改變的次數。新增、刪除、clear會加一。

    @SuppressWarnings("unchecked")
    private Entry<K,V>[] newTable(int n) {//Entry數組,Entry是一個弱引用,
        return (Entry<K,V>[]) new Entry<?,?>[n];
    }

    public WeakHashMap1(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Initial Capacity: "+ initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;// 最大容量只能是MAXIMUM_CAPACITY
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load factor: "+ loadFactor);
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;//capacity是2的冪次方,一直乘以2去接近大小。  找出「大於initialCapacity」的最小的2的冪
        table = newTable(capacity);
        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);//超過12就擴容
    }

    public WeakHashMap1(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public WeakHashMap1() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
    public WeakHashMap1(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY),
             DEFAULT_LOAD_FACTOR);
        putAll(m);
    }
    //若直接插入「null的key」,將其看成弱引用時,會被刪除。這裏對於「key爲null」的清空,都統一替換爲「key爲NULL_KEY」,「NULL_KEY」是「靜態的final常量」。
    private static final Object NULL_KEY = new Object();
    //key是null返回空的Object
    private static Object maskNull(Object key) {
        return (key == null) ? NULL_KEY : key;
    }
    //key是空Object返回null
    static Object unmaskNull(Object key) {
        return (key == NULL_KEY) ? null : key;
    }
    //地址相等
    private static boolean eq(Object x, Object y) {
        return x == y || x.equals(y);
    }
    final int hash(Object k) {
        int h = k.hashCode();//native方法
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
    private static int indexFor(int h, int length) {//就是對長度取模。
        return h & (length-1);//16-1=15。8,4,2,1組合<=15,因此是對16去模。
    }

    //刪除過時的
    private void expungeStaleEntries() {
        for (Object x; (x = queue.poll()) != null; ) {
            synchronized (queue) {
                @SuppressWarnings("unchecked")
                Entry<K,V> e = (Entry<K,V>) x;//queue裏面排隊的是整個Entry,不是key哦。
                int i = indexFor(e.hash, table.length);//對長度取模,不須要探測。鏈式。

                //須要3個指針,prev,p,next.
                Entry<K,V> prev = table[i];
                Entry<K,V> p = prev;
                while (p != null) {//null就找到最後去了。
                    Entry<K,V> next = p.next;
                    if (p == e) {//
                        if (prev == e)//第一個節點
                            table[i] = next;//置換table[i]。e就沒有用了。
                        else
                            prev.next = next;//移除e節點。e就沒有用了。
                        e.value = null; // 幫助 value GC,不幫助key來gc。value爲null會加入queue中。e爲何不置爲null?已經斷開引用了。
                        size--;
                        break;
                    }
                    prev = p;
                    p = next;
                }
            }
        }
    }

    private Entry<K,V>[] getTable() {
        expungeStaleEntries();//gettable時候。會先刪除過時的元素,再返回table。
        return table;
    }
    public int size() {//size也會回收髒數據
        if (size == 0)
            return 0;
        expungeStaleEntries();
        return size;
    }
    public boolean isEmpty() {
        return size() == 0;
    }

    public V get(Object key) {//get時候會回收髒數據
        Object k = maskNull(key);
        int h = hash(k);
        Entry<K,V>[] tab = getTable();
        int index = indexFor(h, tab.length);
        Entry<K,V> e = tab[index];
        while (e != null) {// 在「該hash值對應的鏈表」上查找「鍵值等於key」的元素
            if (e.hash == h && eq(k, e.get()))//hash相等,而且key相等。
                return e.value;
            e = e.next;
        }
        return null;
    }
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }
    public Entry<K,V> getEntry(Object key) {
        Object k = maskNull(key);
        int h = hash(k);
        Entry<K,V>[] tab = getTable();
        int index = indexFor(h, tab.length);
        Entry<K,V> e = tab[index];
        while (e != null && !(e.hash == h && eq(k, e.get())))
            e = e.next;
        return e;
    }
    public V put(K key, V value) {//put也會回收髒數據
        Object k = maskNull(key);//key=null時候,key變爲NULL_KEY = new Object()是一個static final內存,不會加到queue去回收?
        int h = hash(k);
        Entry<K,V>[] tab = getTable();
        int i = indexFor(h, tab.length);
        for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
            if (h == e.hash && eq(k, e.get())) {//覆蓋以前的value
                V oldValue = e.value;
                if (value != oldValue)
                    e.value = value;
                return oldValue;
            }
        }
        modCount++;
        Entry<K,V> e = tab[i];
        tab[i] = new Entry<>(k, value, queue, h, e);//添加新元素
        if (++size >= threshold)//size大於3/4=12就擴容2倍32,
            resize(tab.length * 2);//添加的時候,大於閾值,擴容2倍已是最大容量,就不擴容,繼續放,鏈表無限容量。
        return null;
    }

    void resize(int newCapacity) {//擴容也會回收髒數據
        Entry<K,V>[] oldTable = getTable();
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {//已是最大容量,就不擴容,設置閾值返回。還能夠繼續放,無限容量,由於是鏈表。
            threshold = Integer.MAX_VALUE;
            return;
        }
        Entry<K,V>[] newTable = newTable(newCapacity);//新的Entry數組,
        transfer(oldTable, newTable);//舊的map移到新的map
        table = newTable;
        //擴容時候會消除髒數據,大於3/8=6就設置閾值爲新的24,擴容完畢。
        if (size >= threshold / 2) {
            threshold = (int)(newCapacity * loadFactor);
        //消除髒數據以後小於3/8=6,就不擴容。
        } else {//transfer中已經將原始數組置爲null了,髒數據沒有拷貝過去。
            expungeStaleEntries();
            transfer(newTable, oldTable);//由於在transfer的時候會清除失效的Entry,因此元素個數可能沒有那麼大了,就不須要擴容了
            table = oldTable;
        }
    }

    //舊數組移到新數組,不拷貝髒數據。
    private void transfer(Entry<K,V>[] src, Entry<K,V>[] dest) {
        for (int j = 0; j < src.length; ++j) {
            Entry<K,V> e = src[j];//e最開始是數組第一個元素。
            src[j] = null;
            while (e != null) {
                Entry<K,V> next = e.next;
                Object key = e.get();
                if (key == null) {//髒數據
                    //斷掉後面的引用,前面的引用已經被斷掉了。
                    e.next = null;  // Help GC,key和queue爲何不置爲null?或者直接e置爲null?e已經沒人使用了。
                    e.value = null; //  "   "
                    size--;
                } else {
                    int i = indexFor(e.hash, dest.length);
                    e.next = dest[i];//斷掉了後面的引用,若是後面是髒數據,就沒有人引用髒數據了。
                    dest[i] = e;
                }
                e = next;
            }
        }
    }

    public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;
        if (numKeysToBeAdded > threshold) {//大於閾值擴容
            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);//不是2倍。targetCapacity是目標大小根據numKeysToBeAdded計算
            if (targetCapacity > MAXIMUM_CAPACITY)
                targetCapacity = MAXIMUM_CAPACITY;//擴容後的大小,最大不能超過
            int newCapacity = table.length;//newCapacity是初始如今大小好比16,原始大小。
            while (newCapacity < targetCapacity)
                newCapacity <<= 1;//原始大小一直乘以2接近擴容後大小。大於targetCapacity的最小值。
            if (newCapacity > table.length)
                resize(newCapacity);//擴容
        }
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

    public V remove(Object key) {
        Object k = maskNull(key);
        int h = hash(k);
        Entry<K,V>[] tab = getTable();
        int i = indexFor(h, tab.length);
        Entry<K,V> prev = tab[i];
        Entry<K,V> e = prev;
        //3個指針
        while (e != null) {
            Entry<K,V> 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 (!(o instanceof Map.Entry))
            return false;
        Entry<K,V>[] tab = getTable();
        Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
        Object k = maskNull(entry.getKey());
        int h = hash(k);
        int i = indexFor(h, tab.length);
        Entry<K,V> prev = tab[i];
        Entry<K,V> e = prev;
        //3個指針
        while (e != null) {
            Entry<K,V> 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;
    }

    public void clear() {// 清空WeakHashMap,將全部的元素設爲null
        // 一直出隊,出完爲止
        while (queue.poll() != null) ;
        modCount++;
        Arrays.fill(table, null);//table全是null
        size = 0;
        while (queue.poll() != null) ;
    }

    public boolean containsValue(Object value) {
        if (value==null)
            return containsNullValue();

        Entry<K,V>[] tab = getTable();
        for (int i = tab.length; i-- > 0;)
            for (Entry<K,V> e = tab[i]; e != null; e = e.next)
                if (value.equals(e.value))
                    return true;
        return false;
    }

    private boolean containsNullValue() {
        Entry<K,V>[] tab = getTable();
        for (int i = tab.length; i-- > 0;)
            for (Entry<K,V> e = tab[i]; e != null; e = e.next)
                if (e.value==null)
                    return true;
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Objects.requireNonNull(action);
        int expectedModCount = modCount;

        Entry<K, V>[] tab = getTable();
        for (Entry<K, V> entry : tab) {
            while (entry != null) {
                Object key = entry.get();
                if (key != null) {
                    action.accept((K)WeakHashMap1.unmaskNull(key), entry.value);
                }
                entry = entry.next;

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

    @SuppressWarnings("unchecked")
    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Objects.requireNonNull(function);
        int expectedModCount = modCount;

        Entry<K, V>[] tab = getTable();;
        for (Entry<K, V> entry : tab) {
            while (entry != null) {
                Object key = entry.get();
                if (key != null) {
                    entry.value = function.apply((K)WeakHashMap1.unmaskNull(key), entry.value);
                }
                entry = entry.next;

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

    private transient Set<Map.Entry<K,V>> entrySet;// WeakHashMap的Entry對應的集合

    //返回key集合value集合entry集合的方法。
    public Set<K> keySet() {//Map的key集合轉換成Set
//        Set<K> ks1 = super.keySet();//[k2, k1, k0],也是全部數據都出來了。
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();//new KeySet()時候就把key所有賦值給ks了。
            keySet = ks;
        }
        return ks;
    }
    //value的集合,map改變這個values也改變。collection刪除時候map也會刪除。 不支持添加方法。 
    public Collection<V> values() {
//        Collection<V> vals = super.values();//[v2, v1, v0],也是全部數據都出來了。
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();//new Values()時候就把v所有賦值給vs了。
            values = vs;
        }
        return vs;
    }
    //map改變set也跟着改變。   
    public Set<Map.Entry<K,V>> entrySet() {//Map的全部集合轉成Set
        Set<Map.Entry<K,V>> es = entrySet;//這裏沒值,new EntrySet()以後就有值了就是map全部的元素。
        return es != null ? es : (entrySet = new EntrySet());
    }
//-----------------------------------實體Entry---------------------------------------------------------
    //Entry的key只有Entry引用,gc時候內存不足,key的內存就回收,key置爲null。清理時候,這個髒Entry就會斷開引用等待gc。
    private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {// 它實現了Map.Entry 接口,
        V value;
        final int hash;
        Entry<K,V> next;

        Entry(Object key, V value, ReferenceQueue<Object> queue, int hash, Entry<K,V> next) {
            super(key, queue);//key變成了弱引用。queue是當key僅僅弱引用指向時候,把Entry這個WeakReference加入到的隊列。
            this.value = value;
            this.hash  = hash;
            this.next  = next;//只有key的內存是弱引用指向,gc時候是不會考慮弱引用的,因此key會被gc,value和queue不是弱引用。
        }

        @SuppressWarnings("unchecked")
        public K getKey() {
            return (K) WeakHashMap1.unmaskNull(get());//get()返回key
        }

        public V getValue() {
            return value;
        }

        public V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public boolean equals(Object o) {//key相等==或者equals相等,而且value相等==或者equals相等,就相等。
            if (!(o instanceof 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;
        }

        public int hashCode() {
            K k = getKey();
            V v = getValue();
            //hashcode是經過對象key或者value的native方法來獲取hashcode。Map的hashcode是key的hash值和value的hash值進行異或。
            return Objects.hashCode(k) ^ Objects.hashCode(v);
        }

        public String toString() {
            return getKey() + "=" + getValue();
        }
    }
//-------------------------------3個集合和3個遍歷器-------------------------------------------------
    private abstract class HashIterator<T> implements Iterator<T> {//for循環Iterator接口實例時候,會調用hasNext和next方法。必須重寫hasNext和next方法,其他2個方法不是抽象方法不用重寫。
        private int index;//一開始總大小,不是實際大小。下一次遍歷時的數組的位置。
        private Entry<K,V> entry;//開始爲null。下一次遍歷時的鏈表的位置。
        private Entry<K,V> lastReturned;//開始爲null。遍歷時當前返回的元素。
        private int expectedModCount = modCount;
        private Object nextKey;//下一次遍歷時的元素的key。
        private Object currentKey;//遍歷時當前返回的元素的key。

        HashIterator() {
            index = isEmpty() ? 0 : table.length;//內部類直接使用外部類方法,
        }

        //數組元素的位置index,鏈表中的位置entry。nextKey、entry、
        public boolean hasNext() {
            Entry<K,V>[] t = table;

            while (nextKey == null) {//第一次進來爲null,nextKey!=null就說明有下一個。
                Entry<K,V> e = entry;//第一次進來爲null
                int i = index;
                while (e == null && i > 0)//第一次進來或者到了鏈表的末尾,就爲null。就要查找數組的下一個。
                    e = t[--i];//i開始爲32,一直減到不爲null。這裏是肯定數組元素的位置i。
                entry = e;//找到的元素,hasNext尚未遍歷的下一個元素,
                index = i;//找到的索引,下一次從i開始檢查是否有下一個,
                if (e == null) {//上面的while循環退出時候,e=null。沒有下一個了。
                    currentKey = null;
                    return false;//table中從length開始一個元素都沒有,
                }
                nextKey = e.get(); // e!=null,hasNext尚未遍歷的下一個元素的key,
                if (nextKey == null)//跳過髒數據
                    entry = entry.next;//鏈表的第一個爲髒數據,就要沿着鏈表查找。entry是肯定鏈表的位置。
            }
            return true;
        }

        protected Entry<K,V> nextEntry() {
            //遍歷時候返回一個獨立的EntryIterator對象,expectedModCount = modCount
            //若是遍歷時候map被修改了,modCount改變,expectedModCount不會改變,快速失敗。
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (nextKey == null && !hasNext())
                throw new NoSuchElementException();

            lastReturned = entry;//hasNext()肯定的下一個尚未訪問的entry,
            entry = entry.next;//修改entry爲下一個沒有訪問的元素,會是null。null就說明到了鏈表末尾,就要找數組的下一個元素。
            currentKey = nextKey;//設置當前的key,修改nextKey=null,便於進去hasNext()方法,
            nextKey = null;
            return lastReturned;//返回
        }

        public void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            WeakHashMap1.this.remove(currentKey);
            expectedModCount = modCount;
            lastReturned = null;
            currentKey = null;
        }
    }

    private class ValueIterator extends HashIterator<V> {//遍歷value的遍歷器
        public V next() {
            return nextEntry().value;
        }
    }

    private class KeyIterator extends HashIterator<K> {//遍歷key的遍歷器
        public K next() {
            return nextEntry().getKey();
        }
    }

    private class EntryIterator extends HashIterator<Map.Entry<K,V>> {//遍歷整個map的遍歷器
        public Map.Entry<K,V> next() {//遍歷整個map
            return nextEntry();
        }
    }
    //遍歷時候KeySet,Values,EntrySet返回的是KeyIterator,ValueIterator,EntryIterator。Set都是調用Iterator的方法來遍歷的。
    //KeyIterator,ValueIterator,EntryIterator的 next方法都是用的父類HashIterator的 next方法。
    //KeySet,Values,EntrySet的方法都是WeakHashMap的方法。
    private class KeySet extends AbstractSet<K> {//key的集合。集合裏面有遍歷器。繼承於AbstractSet,說明該集合中沒有重複的Key。
        public Iterator<K> iterator() {
            return new KeyIterator();//key的遍歷器
        }

        public int size() {
            return WeakHashMap1.this.size();
        }

        public boolean contains(Object o) {
            return containsKey(o);
        }

        public boolean remove(Object o) {
            if (containsKey(o)) {
                WeakHashMap1.this.remove(o);
                return true;
            }
            else
                return false;
        }

        public void clear() {
            WeakHashMap1.this.clear();
        }

        public Spliterator<K> spliterator() {
            return new KeySpliterator<>(WeakHashMap1.this, 0, -1, 0, 0);
        }
    }

    private class Values extends AbstractCollection<V> {//value的集合。集合裏面有遍歷器。Values中的元素可以重複。
        public Iterator<V> iterator() {
            return new ValueIterator();//value的遍歷器
        }

        public int size() {
            return WeakHashMap1.this.size();
        }

        public boolean contains(Object o) {
            return containsValue(o);
        }

        public void clear() {
            WeakHashMap1.this.clear();
        }

        public Spliterator<V> spliterator() {
            return new ValueSpliterator<>(WeakHashMap1.this, 0, -1, 0, 0);
        }
    }

    private class EntrySet extends AbstractSet<Map.Entry<K,V>> {//map轉換爲Set的集合。Entry的集合。集合裏面有遍歷器。遍歷map就是這個集合和遍歷器。繼承於AbstractSet,說明該集合中沒有重複的EntrySet。
        public Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();//Entry的遍歷器
        }

        public boolean contains(Object o) {//調用的是map的方法
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            Entry<K,V> candidate = getEntry(e.getKey());
            return candidate != null && candidate.equals(e);
        }

        public boolean remove(Object o) {//調用的是map的方法
            return removeMapping(o);
        }

        public int size() {//調用的是map的方法
            return WeakHashMap1.this.size();
        }

        public void clear() {//調用的是map的方法
            WeakHashMap1.this.clear();
        }

        private List<Map.Entry<K,V>> deepCopy() {//WeakHashMap中的所有元素都拷貝到List中
            List<Map.Entry<K,V>> list = new ArrayList<>(size());
            for (Map.Entry<K,V> e : this)//this是EntrySet
                list.add(new AbstractMap.SimpleEntry<>(e));
            return list;
        }

        public Object[] toArray() {
            return deepCopy().toArray();//List的轉換數組方法
        }

        public <T> T[] toArray(T[] a) {
            return deepCopy().toArray(a);
        }

        public Spliterator<Map.Entry<K,V>> spliterator() {

            return new EntrySpliterator<>(WeakHashMap1.this, 0, -1, 0, 0);
        }
    }
//-------------------------------3個Spliterator,分割器-------------------------------------------------
    //相似於其餘散列拆分器的形式,但跳過死元素。
    static class WeakHashMapSpliterator<K,V> {
        final WeakHashMap1<K,V> map;
        WeakHashMap1.Entry<K,V> current; // 當前數組元素-鏈表的節點
        int index;             // 數組開始位置
        int fence;             // 數組結束位置
        int est;               // 全部鏈表節點個數,
        int expectedModCount;  // 修改次數

        WeakHashMapSpliterator(WeakHashMap1<K,V> 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) {
                WeakHashMap1<K,V> m = map;
                est = m.size();//大小,全部鏈表節點個數,
                expectedModCount = m.modCount;
                hi = fence = m.table.length;//數組大小
            }
            return hi;
        }

        public final long estimateSize() {
            getFence();  
            return (long) est;
        }
    }

    static final class KeySpliterator<K,V> extends WeakHashMapSpliterator<K,V> implements Spliterator<K> {
        KeySpliterator(WeakHashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);//數組開始位置,數組結束位置,鏈表節點個數,修改次數。
        }

        public KeySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                        expectedModCount);//分割前一半數組出去,
        }

        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            WeakHashMap1<K,V> m = map;
            WeakHashMap1.Entry<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;//fence只能爲table.length
            }
            else
                mc = expectedModCount;
            if (tab.length >= hi && (i = index) >= 0 && 
                    (i < (index = hi) || current != null)) {//i等於index,index等於length
                WeakHashMap1.Entry<K,V> p = current;
                current = null; // exhaust
                do {
                    if (p == null)//遍歷一個數組的開頭
                        p = tab[i++];//p=tab[0],p=tab[1],,,,p=tab[hi-1],
                    else {//遍歷這個鏈表
                        Object x = p.get();//獲得key
                        p = p.next;
                        if (x != null) {
                            K k = (K) WeakHashMap1.unmaskNull(x);
                            action.accept(k);
                        }
                    }
                } while (p != null || i < hi);//數組沒有遍歷完,或者鏈表沒遍歷完。
            }
            if (m.modCount != mc)
                throw new ConcurrentModificationException();
        }

        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            WeakHashMap1.Entry<K,V>[] tab = map.table;
            if (tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {//從數組0到末尾。 數組沒有遍歷完,或者鏈表沒遍歷完。
                    if (current == null)//遍歷數組
                        current = tab[index++];
                    else {//遍歷鏈表
                        Object x = current.get();
                        current = current.next;
                        if (x != null) {
                            K k = (K) WeakHashMap1.unmaskNull(x);
                            action.accept(k);
                            if (map.modCount != expectedModCount)//快速失敗
                                throw new ConcurrentModificationException();
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator<K,V> extends WeakHashMapSpliterator<K,V> implements Spliterator<V> {
        ValueSpliterator(WeakHashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public ValueSpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1, expectedModCount);
        }

        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            WeakHashMap1<K,V> m = map;
            WeakHashMap1.Entry<K,V>[] 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)) {
                WeakHashMap1.Entry<K,V> p = current;//當前正在遍歷的元素
                current = null; // exhaust
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        Object x = p.get();
                        V v = p.value;//獲得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<? super V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            WeakHashMap1.Entry<K,V>[] 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;
        }
    }

    static final class EntrySpliterator<K,V> extends WeakHashMapSpliterator<K,V> implements Spliterator<Map.Entry<K,V>> {
        EntrySpliterator(WeakHashMap1<K,V> m, int origin, int fence, int est, int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public EntrySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }


        public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            WeakHashMap1<K,V> m = map;
            WeakHashMap1.Entry<K,V>[] 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)) {
                WeakHashMap1.Entry<K,V> 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) WeakHashMap1.unmaskNull(x);
                            action.accept(new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
                        }
                    }
                } while (p != null || i < hi);//數組沒有遍歷完,或者鏈表沒遍歷完。
            }
            if (m.modCount != mc)
                throw new ConcurrentModificationException();
        }

        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            WeakHashMap1.Entry<K,V>[] 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) WeakHashMap1.unmaskNull(x);
                            action.accept(new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
                            if (map.modCount != expectedModCount)
                                throw new ConcurrentModificationException();
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return Spliterator.DISTINCT;
        }
    }
}
public abstract class AbstractMap1<K,V> implements Map<K,V> {
    protected AbstractMap1() {
    }
    public int size() {
        return entrySet().size();//entrySet()抽象方法
    }
    public boolean isEmpty() {
        return size() == 0;
    }

    public boolean containsValue(Object value) {
        Iterator<Entry<K,V>> i = entrySet().iterator();//entrySet()抽象方法
        if (value==null) {//containsValue  value爲null的。
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getValue()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (value.equals(e.getValue()))
                    return true;
            }
        }
        return false;
    }

    public boolean containsKey(Object key) {
        Iterator<Map.Entry<K,V>> i = entrySet().iterator();
        if (key==null) {//containsKey  key爲null的。
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return true;
            }
        }
        return false;
    }

    public V get(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (key==null) {//get  key爲null的。
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return e.getValue();
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return e.getValue();
            }
        }
        return null;
    }

    public V put(K key, V value) {//子類實現
        throw new UnsupportedOperationException();
    }

    public V remove(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        Entry<K,V> correctEntry = null;
        if (key==null) {//remove  key爲null的。
            while (correctEntry==null && i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    correctEntry = e;
            }
        } else {
            while (correctEntry==null && i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    correctEntry = e;
            }
        }

        V oldValue = null;
        if (correctEntry !=null) {
            oldValue = correctEntry.getValue();
            i.remove();
        }
        return oldValue;
    }

    public void putAll(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

    public void clear() {
        entrySet().clear();
    }
    public abstract Set<Entry<K,V>> entrySet();//Entry的集合
    transient Set<K>        keySet;
    transient Collection<V> values;

    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {//初始化keySet
            ks = new AbstractSet<K>() {//返回匿名對象
                public Iterator<K> iterator() {//for遍歷方法
                    return new Iterator<K>() {//返回匿名對象
                        private Iterator<Entry<K,V>> i = entrySet().iterator();

                        public boolean hasNext() {
                            return i.hasNext();
                        }

                        public K next() {
                            return i.next().getKey();
                        }

                        public void remove() {
                            i.remove();
                        }
                    };
                }

                public int size() {//大小方法
                    return AbstractMap1.this.size();
                }

                public boolean isEmpty() {
                    return AbstractMap1.this.isEmpty();
                }

                public void clear() {
                    AbstractMap1.this.clear();
                }

                public boolean contains(Object k) {//包含方法
                    return AbstractMap1.this.containsKey(k);
                }
            };
            keySet = ks;
        }
        return ks;
    }

    public Collection<V> values() {
        Collection<V> vals = values;
        if (vals == null) {//初始化values
            vals = new AbstractCollection<V>() {//返回匿名對象
                public Iterator<V> iterator() {//for遍歷方法
                    return new Iterator<V>() {//返回匿名對象
                        private Iterator<Entry<K,V>> i = entrySet().iterator();

                        public boolean hasNext() {
                            return i.hasNext();
                        }

                        public V next() {
                            return i.next().getValue();
                        }

                        public void remove() {
                            i.remove();
                        }
                    };
                }

                public int size() {
                    return AbstractMap1.this.size();
                }

                public boolean isEmpty() {
                    return AbstractMap1.this.isEmpty();
                }

                public void clear() {
                    AbstractMap1.this.clear();
                }

                public boolean contains(Object v) {
                    return AbstractMap1.this.containsValue(v);
                }
            };
            values = vals;
        }
        return vals;
    }

    public boolean equals(Object o) {//2個map中每一個元素是否是都相等
        if (o == this)
            return true;
        if (!(o instanceof Map))
            return false;
        Map<?,?> m = (Map<?,?>) o;
        if (m.size() != size())
            return false;
        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();//entrySet()返回EntrySet,iterator()返回EntryIterator。集合裏面有遍歷器。
            while (i.hasNext()) {//hasNext是父類HashIterator的方法
                Entry<K,V> e = i.next();//hasNext是父類HashIterator的方法
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))  //m沒有key
                        return false;
                } else {
                    if (!value.equals(m.get(key)))  //value不爲null,就看value是否相等。
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
        return true;
    }

    public int hashCode() {
        int h = 0;
        Iterator<Entry<K,V>> i = entrySet().iterator();
        while (i.hasNext())
            h += i.next().hashCode();
        return h;
    }

    public String toString() {
        Iterator<Entry<K,V>> i = entrySet().iterator();//entrySet()返回EntrySet,iterator()返回EntryIterator。集合裏面有遍歷器。
        if (! i.hasNext())
            return "{}";

        StringBuilder sb = new StringBuilder();
        sb.append('{');
        for (;;) {
            Entry<K,V> e = i.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key);
            sb.append('=');
            sb.append(value == this ? "(this Map)" : value);
            if (! i.hasNext())
                return sb.append('}').toString();
            sb.append(',').append(' ');
        }
    }

    protected Object clone() throws CloneNotSupportedException {
        AbstractMap1<?,?> result = (AbstractMap1<?,?>)super.clone();//native方法
        result.keySet = null;
        result.values = null;
        return result;
    }

    private static boolean eq(Object o1, Object o2) {
        return o1 == null ? o2 == null : o1.equals(o2);
    }

    public static class SimpleEntry<K,V> implements Entry<K,V>, java.io.Serializable{
        private static final long serialVersionUID = -8499721149061103585L;
        private final K key;
        private V value;

        public SimpleEntry(K key, V value) {
            this.key   = key;
            this.value = value;
        }
        public SimpleEntry(Entry<? extends K, ? extends V> entry) {
            this.key   = entry.getKey();
            this.value = entry.getValue();
        }
        public K getKey() {
            return key;
        }
        public V getValue() {
            return value;
        }
        public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }
        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            return eq(key, e.getKey()) && eq(value, e.getValue());
        }
        public int hashCode() {
            return (key   == null ? 0 :   key.hashCode()) ^
                   (value == null ? 0 : value.hashCode());
        }
        public String toString() {
            return key + "=" + value;
        }
    }

    public static class SimpleImmutableEntry<K,V> implements Entry<K,V>, java.io.Serializable{
        private static final long serialVersionUID = 7138329143949025153L;
        private final K key;
        private final V value;

        public SimpleImmutableEntry(K key, V value) {
            this.key   = key;
            this.value = value;
        }
        public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
            this.key   = entry.getKey();
            this.value = entry.getValue();
        }
        public K getKey() {
            return key;
        }
        public V getValue() {
            return value;
        }
        public V setValue(V value) {
            throw new UnsupportedOperationException();
        }
        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            return eq(key, e.getKey()) && eq(value, e.getValue());
        }
        public int hashCode() {
            return (key   == null ? 0 :   key.hashCode()) ^
                   (value == null ? 0 : value.hashCode());
        }
        public String toString() {
            return key + "=" + value;
        }
    }
}
相關文章
相關標籤/搜索