今日碰见有两方唇枪舌战,争辩 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()
// 实现Serilizable接口,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。
private transient HashMap<E,Object> map;
public boolean contains(Object o) {
return map.containsKey(o);
}
2. HashMap : containsKey()
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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;
}
OK, 真相大白了,看到那个 do while 了吗?还有人说时间复杂度是 O(1) 的我跟谁急啊!