list和set 中 contains()方法的效率

  • list.contains(o) :遍历集合所有元素,用每个元素和传入的元素进行 equals 比较,如果集合元素有 n 个,则会比较 n 次,所以时间复杂度为 O(n) 。方法源码如下:
// 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;
}
  • set.contains(o) :set 集合是用 HashMap 实现的,其中 add 方法将每个元素当做键,以一个object 对象作为值放在 HashMap 中,而 set 的 contains 方法调用了 HashMap 的 containKey 方法,直接获取传入元素的键值对信息做判断,所以 contains 的方法复杂度为 O(1) 。方法源码如下:
// HashSet 中的方法
public boolean add(E e) {
	 // PRESENT 是一个object对象
   return map.put(e, PRESENT)==null;
}
public boolean contains(Object o) {
      return map.containsKey(o);
}


//  HashMap 中的方法
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) {
	        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;
}
//  getNode 方法同样也被hashMap中的get方法所调用
public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
}
  • 在进行contians判断时,全部用Set集合的contains方法,避免踩坑
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值