简体   繁体   English

java.util.HashMap.containsValue() 是如何工作的? 它的时间复杂度是多少?

[英]How does java.util.HashMap.containsValue() work? What is it's time complexity?

I am using java.util.HashMap .我正在使用java.util.HashMap I'm curious to know it's time complexity?我很想知道它的时间复杂度? Is it O(n) or O(1) ?O(n)还是O(1) Does method containsValue() goes for all mapp and check the values or it get immediately?方法 containsValue() 适用于所有 mapp 并检查值还是立即获取? It's very important for time executing.这对执行时间非常重要。

Your answers will probably be here for the general case.对于一般情况,您的答案可能会在这里 For your specific question,对于您的具体问题,

3.1. 3.1. ArrayList The ArrayList in Java is backed by an array... ArrayList Java 中的 ArrayList 由数组支持...

contains() – implementation is based on indexOf(). contains() – 实现基于 indexOf()。 So it will also run in O(n) time所以它也会在 O(n) 时间内运行

The HashMap essentially is a key-value store, which can access it's keys with a complexity of O(1). HashMap 本质上是一个键值存储,它可以以 O(1) 的复杂度访问它的键。 Checking a value, however, there's nothing the HashMap can do but check all values and see if they're equal to the one you're searching.但是,检查一个值时,HashMap 只能检查所有值并查看它们是否与您正在搜索的值相等。

Therefore,所以,

The complexity is O(n) with n being the number of elements in the HashMap.复杂度为 O(n),n 是 HashMap 中元素的数量。

how does method containsValue work in HashMap?方法 containsValue 在 HashMap 中如何工作?

The Javadoc doesn't specify how it is implemented and it might be better than O(n) in theory, however in practice the OpenJDK version uses brute force to find a matching value. Javadoc 没有具体说明它是如何实现的,理论上它可能比 O(n) 更好,但实际上 OpenJDK 版本使用蛮力来找到匹配值。

// from OpenJDK Java 8.
// the implementation could be different for another implementation, or subclass.
public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                if ((v = e.value) == value ||
                    (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM