What is the time complexity performance of HashSet.contains() in Java?

前端 未结 2 1047
小蘑菇
小蘑菇 2020-11-28 08:47

I\'m tempted to think that the HashSet.contains(Object) method performs in constant time. It simply gets the hash code of an object and then looks it up in a hash table.

2条回答
  •  庸人自扰
    2020-11-28 09:03

    It runs in O(1) expected time, as any hash table (assuming the hash function is decent). It is backed by a HashMap where the key is the Object.

    Two objects might have the same hash code, but the HashSet wouldn't think they are identical, unless the equals method for these objects says they are the same (i.e. returns true).

    The contains method calls (indirectly) getEntry of HashMap, where key is the Object for which you wish to know if it's in the HashSet.

    As you can see below, two objects can be stored in the HashMap/HashSet even if their key is mapped to the same value by the hash function. The method iterates over all keys that have the same hash value, and performs equals on each one to find the matching key.

    final Entry getEntry(Object key) {
             int hash = (key == null) ? 0 : hash(key.hashCode());
             for (Entry e = table[indexFor(hash, table.length)];
                  e != null;
                  e = e.next) {
                 Object k;
                 if (e.hash == hash &&
                     ((k = e.key) == key || (key != null && key.equals(k))))
                     return e;
             }
             return null;
         }
    

提交回复
热议问题