服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java list与set中contains()方法效率案例详解

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

2021-12-10 13:27小风的笔记 Java教程

这篇文章主要介绍了Java list与set中contains()方法效率案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  • list.contains(o) :遍历集合所有元素,用每个元素和传入的元素进行 equals 比较,如果集合元素有 n 个,则会比较 n 次,所以时间复杂度为 O(n) 。方法源码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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) 。方法源码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 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方法,避免踩坑

到此这篇关于Java list与set中contains()方法效率案例详解的文章就介绍到这了,更多相关Java list与set中contains()方法效率内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_43771403/article/details/120002486

延伸 · 阅读

精彩推荐