由一次Set删除失效引发的源码探究

引子

记一次在工作当中,有这样一个业务场景:

​ 在通过接口返回前,需要为一个set中的所有元素赋值,然后剔除掉一些不符合条件的元素,最后返回。代码结构大概如下:

代码

Set<Item> sets = Sets.newHashSet();
sets.addAll(items);
...
setValue(sets) ;

//剔除sets中不符合条件的元素
**sets.removeIf(Predicate filter);**

//为set中的元素设置属性
private setValue(Set<Item> sets){
    for(Item:item sets){
        ...
    }
}

看似是一段clean code,逻辑清晰,实则蕴藏杀机;大家大概一眼就能看出其中玄机,其中的removeif压根就不起作用啊,可是菜如狗的我还没发现其中一二,还在慢慢的debug,写单元测试,并单纯的以为是编译的问题...终于一位同事在review之后,一语点醒我:"removeIf 是如何找到你要删除的元素的呢?"

原因

终于,我在查看了set集合removeIf与addAll的原理以后,顿悟了,主要有四个关键点:

  1. HashSet底层实际上就是一个HashMap, 节选一段hashSet的构造方法就能发现,其中key为要添加的元素,value为Present,如下:

        // Dummy value to associate with an Object in the backing Map
        private static final Object PRESENT = new Object();
    
        /**
         * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
         * default initial capacity (16) and load factor (0.75).
         */
        public HashSet() {
            map = new HashMap<>();
        }
  2. 在向set中添加元素调用addAll方法是,实际上也是循环调用set的add方法,而实际上也是调用map的put方法。

    public boolean addAll(Collection<? extends E> c) {
            boolean modified = false;
            for (E e : c)
                if (add(e))
                    modified = true;
            return modified;
        }
    
    public boolean add(E e) {
            return map.put(e, PRESENT)==null;
     }
  3. set在执行removeIf操作时,实际上调用的是 iterator的remove操作,而collection继承了iterator,set继承了collection,底层通过hashmap实现,(@w@~ 有点绕), 实际上就是调用的map的remove方法,如下:

    default boolean removeIf(Predicate<? super E> filter) {
            Objects.requireNonNull(filter);
            boolean removed = false;
            final Iterator<E> each = iterator();
            while (each.hasNext()) {
                if (filter.test(each.next())) {
                    each.remove();
                    removed = true;
                }
            }
            return removed;
        }
  4. 现在我们了解到,set在添加或者是删除元素均是调用的map的对应的方法,而hashMap是通过数据+链表+红黑树实现的,但是map是如何找到这些元素,并进行相应的添加或删除操作呢?如下put方法,

    首先调用了hash方法计算key的hash值,在hash方法则调用了key的hashCode方法以及移位以及逻辑异或运算。

    然后又调用了putVal方法,在该方法中我们了解到hashMap主要是通过key的该hash值进行寻找元素的插入位置的,若已存在,值覆盖,否则插入,其中的其他方法这里不再展开。

    //首先是put方法的实现
     public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
     }
    //hash方法
    static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    //put又调用的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)
                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;
        }
    
    

    接着是remove方法源码如下,我们发现,在remove方法中,仍然首先调用hash方法计算key的hash值,然后调用removeNode进行删除操作,这里在删除时移动其他元素的方法不再展开,我们可以知道,remove方法仍然是通过key的hash来查询要删除的元素的。

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

通过分析上述的removeIf与addAll源码可知,底层均调用的map的put与remove方法。同样的,set在add元素时,首先会计算元素的hash值,来寻找元素的插入位置;在删除元素时,同样会重新计算元素的hash值来查询要删除的元素;而hash方法主要是通过元素的hashCode方法来计算的,那么出现删除失效的问题一定是与hahsCode方法有关的,我查了下该类,果然,hashCode方法被重写了........所以在add与remove时,对应元素的hashCode是不同的,因为这之间我为元素赋了值.....当然,能找到原因还是很开心的~

解决办法

  1. 最笨的,再新建一个集合,遍历,把符合条件的元素留下

  2. 挪一下方法的位置,不要在add与remove之间为相应元素属性复制,这当然要看你自己的业务场景与hashCode的重写逻辑咯

  3. 重写hashcode方法与equals方法。

猜你喜欢

转载自www.cnblogs.com/wtlife/p/11962198.html