Hos*_*ein 47 java performance hashmap time-complexity
我需要知道:Java中HashMap.containsKey()的时间复杂度是多少?
Mic*_*rdt 59
假设散列函数在桶之间正确地分散元素,该实现为基本操作(get和put)提供了恒定时间性能.
因为containsKey()
它只是get()
抛弃了检索到的值,所以它是O(1)(假设哈希函数再次正常工作).
这是O(1)
一般的,但在最坏的情况下,O(n)
public boolean containsKey(Object key) {
352 return getEntry(key) != null;
353 }
354
355 /**
356 * Returns the entry associated with the specified key in the
357 * HashMap. Returns null if the HashMap contains no mapping
358 * for the key.
359 */
360 final Entry<K,V> getEntry(Object key) {
361 int hash = (key == null) ? 0 : hash(key.hashCode());
362 for (Entry<K,V> e = table[indexFor(hash, table.length)];
363 e != null;
364 e = e.next) {
365 Object k;
366 if (e.hash == hash &&
367 ((k = e.key) == key || (key != null && key.equals(k))))
368 return e;
369 }
370 return null;
371 }
Run Code Online (Sandbox Code Playgroud)
JDK-1.8的时间复杂度发生containsKey
了变化,正如其他人提到的那样,它处于理想情况.然而,在碰撞其中的情况下是,频段存储它们超过某个阈值称为后碰撞元件不是线性的了,这是等于8,O(1)
keys
Comparable
TREEIFY_THRESHOLD
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
Run Code Online (Sandbox Code Playgroud)
换句话说,TreeNodes
将使用(类似于那些TreeMap
)来存储箱子(即:红黑树结构),这使我们O(lgn)
在碰撞的情况下具有复杂性.
这同样适用于get(key)
两个方法在getNode
内部调用的位置
注意:这里的n是大小bin
而不是大小HashMap
归档时间: |
|
查看次数: |
51957 次 |
最近记录: |