Time Complexity of HashMap methods

前端 未结 5 1038
走了就别回头了
走了就别回头了 2020-12-13 19:21

Since i\'m working around time complexity, i\'ve been searching through the oracle Java class library for the time complexity of some standard methods used on Lists, Maps an

5条回答
  •  庸人自扰
    2020-12-13 20:02

    The code for remove(as in rt.jar for HashMap) is:

    /**
     * Removes and returns the entry associated with the specified key
     * in the HashMap.  Returns null if the HashMap contains no mapping
     * for this key.
     */
    final Entry removeEntryForKey(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        int i = indexFor(hash, table.length);
        Entry prev = table[i];
        Entry e = prev;
    
        while (e != null) {
            Entry next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }
    
        return e;
    }
    

    Clearly, the worst case is O(n).

提交回复
热议问题