List与Set的contains方法效率问题

  1. ArrayList 中contains()原理
    通过遍历集合,借助equals()比较
public boolean contains(Object o) {
    
    
        return indexOf(o) >= 0;
    }
public int indexOf(Object o) {
    
    
        if (o == null) {
    
    
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
    
    
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
  1. HashSet 中contains()原理
    先借助hashCode(),再借助equals()比较;结合HashMap底层结构及添加元素的原理可知:HashSet 中contains()效率高于ArrayList
public boolean contains(Object o) {
    
    
        return map.containsKey(o);
    }
public boolean containsKey(Object key) {
    
    
        return getNode(hash(key), key) != null;
    }
static final int hash(Object key) {
    
    
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
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;
    }

猜你喜欢

转载自blog.csdn.net/weixin_51681634/article/details/112908691
今日推荐