Set---HashSet-LinkedHashSet

概述

Hash table and linked list implementation of the <tt>Set</tt> interface, with predictable iteration order.
This implementation differs from <tt>HashSet</tt> in that it maintains a doubly-linked list running through all of its entries.
This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (<i>insertion-order</i>).

Hash表+LinkedList 的Set实现,支持可预测的iterator顺序;

LinkedHashSet是双向链表

LinkedHashSet默认的iterator顺序是 元素被insert的顺序(插入排序);

 

It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation:

void foo(Set s) {  Set copy = new LinkedHashSet(s); }

LinkedHashSet通常被用来 当做与原集合相同顺序的copy

 

This class provides all of the optional <tt>Set</tt> operations, and permits null elements.
Like <tt>HashSet</tt>, it provides constant-time performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and <tt>remove</tt>), assuming the hash function disperses elements properly among the buckets.

LinkedHashSet支持所有Set操作,允许null

LinkedHashSet的add、contains、remove 花费 O(1)时间复杂度,因为Hash将元素分散在buckets;

 

A linked hash set has two parameters that affect its performance: <i>initial capacity</i> and <i>load factor</i>.  

LinkedHashSet有2个参数影响性能:initial capacity、load factor;

 

Note that this implementation is not synchronized.
If multiple threads access a linked hash set concurrently, and at least one of the threads modifies the set, it <em>must</em> be synchronized externally.

If no such object exists, the set should be "wrapped" using the {@link Collections#synchronizedSet Collections.synchronizedSet} method.

 

LinkedHashSet是线程非同步的;

如果多个线程并发修改,需要在外部进行同步;

可以使用Collections.synchronizedSet;

 

The iterators returned by this class's <tt>iterator</tt> method are <em>fail-fast</em>: if the set is modified at any time after the iterator is created, in any way except through the iterator's own <tt>remove</tt> method, the iterator will throw a {@link ConcurrentModificationException}.

LinkedHashSet的iterator是fail-fast:如果在iterator时,remove(除iterator的remove),将会抛出ConcurrentModificationException;

 

链路

new LinkedHashSet<>(10)

// java.util.LinkedHashSet.LinkedHashSet(int)
    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    // java.util.HashSet.HashSet(int, float, boolean)

    /**
     * Constructs a new, empty linked hash set. (This package private constructor is only used by LinkedHashSet.)
     * The backing HashMap instance is a LinkedHashMap with the specified initial capacity and the specified load factor.
     *  底层使用的是LinkedHashMap
     * @param dummy 忽略(与其他构造器进行区分)
     */
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

  

add

// java.util.HashSet.add
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

    // java.util.HashMap.put
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    // java.util.HashMap.putVal
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);                                           // 创建新的LinkedHashMap的node && link到列表尾部
        else {
            HashMap.Node<K,V> e; K k;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof HashMap.TreeNode)
                e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    // java.util.LinkedHashMap.newNode
    HashMap.Node<K,V> newNode(int hash, K key, V value, HashMap.Node<K,V> e) {
        LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e);             
        linkNodeLast(p);
        return p;
    }
    
    // java.util.LinkedHashMap.linkNodeLast
    private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
        LinkedHashMap.Entry<K,V> last = tail;
        tail = p;
        if (last == null)
            head = p;
        else {
            p.before = last;
            last.after = p;
        }
    }

  

 

linkedHashSet.iterator()

Set<String> linkedHashSet = new LinkedHashSet<>(10);
        linkedHashSet.add("a");
        linkedHashSet.add("d");
        linkedHashSet.add("c");
        linkedHashSet.add("b");
        
        Iterator<String> iterator = linkedHashSet.iterator();
        while (iterator.hasNext()) {    // java.util.LinkedHashMap.LinkedHashIterator.hasNext
            String next = iterator.next();// java.util.LinkedHashMap.LinkedKeyIterator.next -> java.util.LinkedHashMap.LinkedHashIterator.nextNode
            iterator.remove();  // java.util.LinkedHashMap.LinkedHashIterator.remove
        }

  

// java.util.HashSet.iterator
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }
    
    // java.util.LinkedHashMap.keySet
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new LinkedHashMap.LinkedKeySet();
            keySet = ks;
        }
        return ks;
    }
    
    // java.util.LinkedHashMap.LinkedKeySet
    final class LinkedKeySet extends AbstractSet<K> {
        
    }
    
    // java.util.LinkedHashMap.LinkedKeySet.iterator
    final class LinkedKeySet extends AbstractSet<K> {
        public final Iterator<K> iterator() {
            return new LinkedHashMap.LinkedKeyIterator();
        }
    }
    
    // java.util.LinkedHashMap.LinkedKeyIterator
    final class LinkedKeyIterator extends LinkedHashIterator implements Iterator<K> {
        public final K next() { return nextNode().getKey(); }
    }
    
    // java.util.LinkedHashMap.LinkedHashIterator
    abstract class LinkedHashIterator {
        public final boolean hasNext() {
            return next != null;
        }

        final LinkedHashMap.Entry<K,V> nextNode() {
            LinkedHashMap.Entry<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            current = e;
            next = e.after;
            return e;
        }

        public final void remove() {
            HashMap.Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

  

 

posted on 2023-11-09 11:24  anpeiyong  阅读(9)  评论(0编辑  收藏  举报

导航