Set和List的时间复杂度

变量申明、函数返回一般用通用类型 例如:

Set<String> list=new HashSet<>();
List<String> list=new ArrayList<>();

ArrayList本质就是通过数组实现的,查找一个元素是否包含要用到遍历,时间复杂度是O(n) 而HashSetHashSet的查找是通过HashMap的KeySet来实现的,判断是否包含某个元素的实现,时间复杂度是O(1)

ArrayList判断是否包含某个元素的源码实现:

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

HashSet判断是否包含某个元素的源码实现:

public boolean contains(Object o) {
          
   
        return map.containsKey(o);
    }

 public boolean containsKey(Object key) {
          
   
        return getNode(hash(key), key) != null;
    }

   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) {
          
    //直接通过hash确定元素位置,不用从头遍历
            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;
    }
经验分享 程序员 微信小程序 职场和发展