简体   繁体   English

哈希表中包含方法的时间复杂度?

[英]time complexity of contains method in hashtable?

I just saw the code of contains method in java.util.Hashtable.java. 我刚刚在java.util.Hashtable.java中看到了contains方法的代码。 It has a loop that scans through each entry in the Hashtable and compares it with the argument passed. 它有一个循环,它扫描Hashtable中的每个条目,并将其与传递的参数进行比较。

I read that contains method takes constant time. 我读到包含方法需要恒定的时间。 How is it possible when it has a loop that scans through each entry. 当它有一个扫描每个条目的循环时,它怎么可能。

 public synchronized boolean contains(Object value) {
if (value == null) {
    throw new NullPointerException();
}

Entry tab[] = table;
for (int i = tab.length ; i-- > 0 ;) {
    for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
    if (e.value.equals(value)) {
        return true;
    }
    }
}
return false;
}

Hashtable.contains() tries to find an entry with an equal value . Hashtable.contains()尝试查找具有相等的条目。 It's lookups by key which are constant time (in the usual case) in hash tables. 它是按键查找的,它是哈希表中的常量时间(通常情况下)。

The docs clarify this: 文档澄清了这一点:

Tests if some key maps into the specified value in this hashtable. 测试某些键是否映射到此哈希表中的指定值。 This operation is more expensive than the containsKey method. 此操作比containsKey方法更昂贵。

Note that this method is identical in functionality to containsValue, (which is part of the Map interface in the collections framework). 请注意,此方法在功能上与containsValue相同(它是集合框架中Map接口的一部分)。

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

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