Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of equals() in HashMap and SortedMap

I am trying to figure out the computational complexity of equals() in both HashMap and TreeMap in Java. Now, you might say it should be same in both cases as both HashMap and TreeMap inherit the same implementation from AbstractMap. However, I am in need of some explanation before I can fully accept that.

Here is what confuses me. Part of the explanation in overridden equals() in AbstractMap documentation is:

More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()).

The documentation is not clear on whether the sets returned by the entrySet are HashSet or SortedSet or something else. In my view this is important to know as it would impact the overall analysis.

If sets returned by entrySet() are of type HashSet then two sets can compared in O(n) [cost of equals in case of two hash sets]. However, if they are of type SortedSet then they can be compared in O(nlogn) [cost of equals in case of two sorted sets]. Consequently, complexity of equals() in case of HashMap would be different then in case of SortedMap, or at least it should be based on my reasoning.

I strongly suspect I am wrong somewhere in my reasoning, so feel free to tell me where I am wrong. What is the correct reasoning. And, finally I am interested in the complexity of equals() in case of HashMap and SortedMap. Thanks.

like image 264
Waqas Avatar asked Oct 03 '22 22:10

Waqas


1 Answers

I believe you are right about the complexity of both methods. Since they both inherit their equals implementation from AbstractMap, it is worthwhile inspecting the source code for AbstractMap. The relevant portion is as follows:

Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
    return false;

Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
    if (!(m.get(key)==null && m.containsKey(key)))
        return false;
} else {
    if (!value.equals(m.get(key)))
        return false;
}
return true;

Note that it calls the get and containsKey methods within the inner loop which are overridden by their subclasses. Since HashMap implements these in O(1) while TreeMap implements them in O(log n), that leads to the overall equals complexity of O(n) for Hashmap and O(n log n) for TreeMap.

like image 118
nitegazer2003 Avatar answered Oct 10 '22 20:10

nitegazer2003