Java:Set 的 contains() 方法 时间复杂度

今日碰见有两方唇枪舌战,争辩 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) 的我跟谁急啊!

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值