Set集合

73 阅读4分钟
    1. HashSet 实现了Set接口 HashSet实际上是HashMap

    public HashSet() {
        map = new HashMap<>();
    }

    2. HashSet添加元素时,会先计算得到hash值,然后转成索引值,然后找到对应存储数据的table,查看当前索引值下是否有元素
    如果没有则直接插入,如果有,则调用equals进行比较,如果比较相同,则放弃添加,反之则添加到最后(链表)

    3. 在Java8中,如果一条链表的元素个数 > 8 并且table的大小 >= 64 ,就会转换成红黑树

    4. add()
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;  ->  private static final Object PRESENT = new Object(); // 占位目的 ,返回null表示成功
    }

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    static final int hash(Object key) {  // 计算hash值
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    5. putVal()
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i; // 辅助变量
    if ((tab = table) == null || (n = tab.length) == 0) // 这里的table其实就是 HashMap的一个数组,类型是Node[]
        n = (tab = resize()).length;  // resize() 返回一个长度为16的数组
    if ((p = tab[i = (n - 1) & hash]) == null)
    // 根据Key值,得到hash 去计算该key应该存放到table表的那个索引位置,并且把这个位置的变量赋值给p,然后判断p是否为空,为空则创建新的节点
        tab[i] = newNode(hash, key, value, null);
    else {              // 重复元素添加时,则会走此分支
        Node<K,V> e; K k;
        if (p.hash == hash &&  // 如果当前索引位置对应的链表的第一个元素和准备添加的key的hash值一样,
        // 且满足下面两个条件之一
        // 准备加入的key和 p 指向的Node节点的key是同一对象
        // p 指向的Node节点的key的equals()和准备加入的key比较后相同
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)  // 判断p是否是红黑树,是则调用putTreeVal
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {  // 如果table对应的索引位置,已经是一个链表结构,则遍历该链表,依次和该链表的每一个元素进行比较,如果都不相同则直接添加,如果相同则不添加,break跳出循环
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {   // p 值得是对应下标下的Node节点对象 ,如果p的下一节点为空,说明p是尾节点
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st // 添加数据后,马上判断该链表是否已经有8个节点,如果达到8个节点,
                    但是数组长度还没到64,则每添加一个元素,则会再次触发数组扩容机制,直到table长度> 64 ,则对当前链表进行树化(红黑树)
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash && // 如果p的下一节点为空,说明p不是尾节点再进行比较
                    ((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) // 查看是否需要扩容  ++size:就是每往table加入一个节点的记录值Node(k,v,h,next)
        resize();
    afterNodeInsertion(evict);    ->  void afterNodeInsertion(boolean evict) { } 空方法,为开发者提供
    return null; // 返回null表示成功
    }

    6. resize() ->
    final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table; // 把table 指向一个空数组
    int oldCap = (oldTab == null) ? 0 : oldTab.length; // 如果数组为空,则返回0否则返回对应数组长度
    int oldThr = threshold; // 临界值 ->  int threshold; 初始值为0
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;  // 赋值为默认长度 16  ->     static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 左移 其实就是 1*2*2*2*2
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 临界值(加载因子) static final float DEFAULT_LOAD_FACTOR = 0.75f; 当数组长度大于(16*0.75)时触发扩容机制
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr; // 记录临界值
    @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;  // 赋值给 table 16
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}
/*
    1. LinkedHashSet 底层是LinkedHashMap,底层维护了数组+双向链表
    2. LinkedHashSet是根据元素的hashCode来决定元素的存放位置,同时利用链表维护元素的次序
    3. LinkedHashSet不可以添加重复数据
    4. 在LinkedHashSet中维护了一个hash表和双向链表(head,tail),每个节点有before和after属性
    5. 在添加数据时,先求hash值,再求索引,确认该元素在table的位置,然后将添加的元素加入到双向链表,如果已经存则不添加
    6. LinkedHashSet加入元素的顺序和取出元素的顺序一致
    7. 数组是HashMap$Node[] 存放的元素是LinkedHashMap$Entry类型


    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

    public LinkedHashSet() {
        super(16, .75f, true);
    }

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }
 */
public static void main(String[] args) {

        Node[] table = new Node[16]; // 新增数组 -> 每隔数组存放一个 Node 对象

        Node<String> varAble1 = new Node<>("varAble1", null);

        table[2] = varAble1; // 将 Node 放到数组

        Node<String> varAble2 = new Node<>("varAble2", null);

        varAble1.next = varAble2; // 形成链表 varAble1 指向 varAble2

        Node<String> varAble3 = new Node<>("varAble3", null);

        varAble2.next = varAble3; // 形成链表 varAble2 指向 varAble3

    }
}

class Node<E> {

    E element;

    Node<E> next;

    public Node(E element, Node<E> next) {
        this.element = element;
        this.next = next;
    }