What is the time complexity of HashMap.containsKey() in java?

后端 未结 4 1286
北荒
北荒 2020-12-02 11:59

I need to know: What is the time complexity of HashMap.containsKey() in java?

4条回答
  •  离开以前
    2020-12-02 12:42

    It is O(1) in general, however in worst case it is 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 getEntry(Object key) {
      361           int hash = (key == null) ? 0 : hash(key.hashCode());
      362           for (Entry 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       }
    

提交回复
热议问题