今日碰见有两方唇枪舌战,争辩 Set 的时间复杂度。我腹诽:居然有人认为它是 O(1) 吗?但我人怂胆小,宛如街头争霸时两大帮派摩拳擦掌时弱小可怜但充满正义感的小豆芽。所谓 “Talk is cheap. Show me the code.”,是时候搬出 JDK 了。
1. HashSet : contains()
引用代码
HashSet
<Integer> integerSet
= new HashSet<>();
integerSet
.add(1);
System
.out
.println(integerSet
.contains(1));
contains()
private transient HashMap
<E,Object> map
;
public boolean contains(Object o
) {
return map
.containsKey(o
);
}
2. HashMap : containsKey()
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
&&
((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
;
}
OK, 真相大白了,看到那个 do while 了吗?还有人说时间复杂度是 O(1) 的我跟谁急啊!