Java list与set中contains()方法效率 Java list与set中contains()方法效率案例详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java list与set中contains()方法效率 Java list与set中contains()方法效率案例详解

小风的笔记   2021-08-31 我要评论
想了解Java list与set中contains()方法效率案例详解的相关内容吗,小风的笔记在本文为您仔细讲解Java list与set中contains()方法效率的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,list与set中contains()效率,Java,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方法,避免踩坑

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们