首页 > 其他分享 >Set---HashSet-LinkedHashSet

Set---HashSet-LinkedHashSet

时间:2023-11-09 11:33:04浏览次数:31  
标签:Set LinkedHashSet iterator --- key hash null LinkedHashMap

概述

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;
        }
    }

  

 

标签:Set,LinkedHashSet,iterator,---,key,hash,null,LinkedHashMap
From: https://www.cnblogs.com/anpeiyong/p/17819323.html

相关文章

  • 线程安全集合(JDK1.5之前和之后)、CopyOnWriteArrayList、CopyOnWriteArraySet
    JDK1.5之前JDK1.5之前:Collections.synchronizedList JDK1.5之后CopyOnWriteArrayList   CopyOnWriteArraySet    ......
  • 表碎片整理时shrink和move如何选择 --高水位回收 转:http://blog.itpub.net/29821
    整理表碎片通常的方法是move表,当然move是不能在线进行的,而且move后相应的索引也会失效,oracle针对上述不足,在10g时加入了shrink,那这个方法能不能在生产中使用呢?     shrink的一个优点是能在线进行,不影响表上的DML操作,当然,并发的DML操作在shrink结束的时刻会出现短暂的block;s......
  • STL之unordered_set与unordered_map的模拟实现(万字长文详解)
    unordered_set与unordered_map的模拟实现哈希节点类#pragmaonce#include<iostream>#include<vector>namespaceMySTL{template<classT>structHashNode{HashNode(constT&data=T())......
  • mysql-utilities对比两个库数据一致性
    1.安装mysql-utilities首先yum源安装python,之后根据python版本下载安装mysql-connector-pythonyuminstallpythonpython--versionpython2.6.6下载地址:https://downloads.mysql.com/archives/c-python/rpm-ivhmysql-connector-python-2.1.6-1.el6.x86_64.rpmwhichpython之后......
  • 【misc】[HNCTF 2022 Week1]lake lake lake(JAIL) --沙盒逃逸,globals函数泄露全局变量
    查看附件内容这道题的逻辑就是可以让你输入1或者2,进入各自的函数去执行功能func函数:deffunc():  code=input(">")  if(len(code)>9):    returnprint("you'rehacker!")  try:    print(eval(code))  except:    pass......
  • Sol - P9796
    数学构造题。我们知道,分数相加有通分这一步。所以当\(n=p^k\)且\(k\)为正整数,\(p\)为质数时无解,我们构造不出来这样的分数,使得通分完后分母不小于\(n\)。证明:根据唯一分解定理以及求解多个数的最小公倍数的过程,可以得到\(b_i=x\timesp^m(m\geq0)\),其中\(x\)为正......
  • 通义千问, 文心一言, ChatGLM, GPT-4, Llama2, DevOps 能力评测
    引言“克隆dev环境到test环境,等所有服务运行正常之后,把访问地址告诉我”,“检查所有项目,告诉我有哪些服务不正常,给出异常原因和修复建议”,在过去的工程师生涯中,也曾幻想过能够通过这样的自然语言指令来完成运维任务,如今AI助手Appilot利用LLM蕴藏的神奇力量,将这一切变成......
  • 【misc】[HNCTF 2022 Week1]python2 input(JAIL) --沙盒逃逸,python2环境
    查看附件,这次有点不太一样,这次是python2的环境只有一个input函数,但是python2的input函数可是不太一样:在python2中,input函数从标准输入接收输入,并且自动eval求值,返回求出来的值在python2中,raw_input函数从标准输入接收输入,并返回输入字符串在python3中,input函数从标准输入接收输......
  • 无涯教程-批处理 - Nested If 语句函数
    有时,要求彼此之间嵌入多个"if"语句。以下是此声明的一般形式。if(condition1)if(condition2)do_something因此,仅当满足condition1和condition2时,才会执行do_something块中的代码。以下是如何使用嵌套if语句的示例。@echooffSET/Aa=5SET/Ab=10if%a%==5if%b......
  • 2.品牌浮动布局----纯文字
    品牌浮动布局,纯文字类型1<!DOCTYPEhtml>2<html>3<head>4<style>5.flex-container{6display:flex;7flex-wrap:wrap;8background-color:DodgerBlue;9}1011.flex-container>div{12background-color:#f1f1f1......