HashSet源码&为什么在去重集合中加入自定义对象需要重写equals方法和hashCode方法

HashSet源码&为什么在去重集合中加入自定义对象需要重写equals方法和hashCode方法

写在前面:20221010复习的时候查到了这个问题,在这里记录下

HashSet源码部分

我们知道,HashSet底层是HashMap,所以它的源码其实是HashMap的源码;这里只涉及相关的方法-->put() containsKey() remove()

  • put()
  • 简单讲解:
    • 调用put方法后,其实是再次调用了putVal方法
    • 在putVal方法中,首先会判断承载hash点的数组是否为空,如果为空则创建新的
    • 保证数组可用之后,会先判断对应hash值得位置是否为空,如果为空则直接加进去
    • 如果不为空则开始判断加入结点的哈希码是否等于对应hash位置的哈希码,如果不等则进一步判断key的地址和内容是否相同-->其中地址使用==,内容使用equals(这里其实就揭示了为什么要重写hashCode和equals方法,如果不重写则会调用Object类的方法,而所有新生成的对象Object类中的HashCode都不相同,所以会在加入过程中加入重复的元素)
      • 如果都不相等,则赋值然后覆盖老的value(这里有一个onluIfAbsent参数,如果这个值为true,则只有当老的value为null时才会覆盖)
    • 如果上一个步骤的判断不成立,则会开始判断是否是TreeNode,如果是TreeNode则将工作交给Tree的putTreeVal方法(说明已经超过八个元素了,变换为红黑树,而红黑树插入过程中会判重)
    • 如果上一个步骤还不成立,则开始遍历该hash结点的链表,如果遍历到尾部还没有找到相同key的node,就直接插入,插入后长度如果大于设置的阈值,则开始转化为红黑树,如果找到则直接退出循环,开始赋值过程
    • 最后插入完毕,开始内部的计数,如果大小大于阈值,也会触发resize
    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            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 TreeNode)
                e = ((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;
    }
  • containsKey()
  • 简单讲解:
    • 内部再次调用getNode方法,如果返回不为空,则返回true,否则为false
    • 先判断数组是否为空,如果为空直接返回null
    • 如果不为空,则开始判断hash对应结点和其下的链表结点是否有重复的值,如果有则返回它,如果没有则返回null
    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    /**
     * Implements Map.get and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
  • remove()
  • 还是再次调用了removeNode方法,内部和上述两个差不多,无非就是循环判断链表,如果节点类型为树节点,则转为循环判断红黑树
    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    /**
     * Implements Map.remove and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

为什么在去重集合中加入自定义对象需要重写equals方法和hashCode方法

  • 其实在上面的put方法讲解中已经提到了,这两个方法其实是支持我们自定义判重的条件的,如果不重写,则会使用Object的HashCode判断,则不一定符合我们的预期

以上
希望对后来者有所帮助

posted @ 2022-10-10 21:26  醉生梦死_0423  阅读(24)  评论(0编辑  收藏  举报