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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | // 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()
1 2 3 4 5 6 7 8 9 10 11 | 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 } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // 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; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)