Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the time complexity of contains() of a Set view?

If I have a TreeSet and I use contains() on the Set view of keySet() is the time complexity O(1)?

Map<String, Integer> map1 = new TreeMap<>();
map1.keySet().contains(xyz);

I am wondering as for example contains() for HashSet and LinkedHashSet is O(1) but for a TreeSet is O(log(N)) but the keySet() method is not returning a HashSet, LinkedSet or TreeSet but just a Set view in general thus making me unsure.

Best regards

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I checked here and here but could not find any performance related information.

EDIT:
I have since found this question: What is a view of a collection?
This makes me think the call of contains() is then made by the TreeMap and not the Set and would therefore be O(log(N))?

>Solution :

map1.keySet().contains(xyz); is 100% identical to calling map1.containsKey(xyz);. You can verify it by looking at the source:

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
    // […]

    public Set<K> keySet() {
        return navigableKeySet();
    }

    /**
     * @since 1.6
     */
    public NavigableSet<K> navigableKeySet() {
        KeySet<K> nks = navigableKeySet;
        return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
    }

    // […]

    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
        private final NavigableMap<E, ?> m;
        KeySet(NavigableMap<E,?> map) { m = map; }

        // […]

        public boolean contains(Object o) { return m.containsKey(o); } // [<-- delegates back to map]

        // […]
    }

    // ...
}

=> The key set has the same runtime characteristics as the collection itself. In case of a TreeMap that’s O(log(n)) for the contains operation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading