In Java, contains(o) returns true if the TreeSet holds an element matching o, and false otherwise.
Rather than scanning element by element, contains() walks the red-black tree in O(log n) time. Matching uses compareTo() or the set's Comparator returning 0, not equals().
An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.
For a TreeSet backed by a custom comparator that ignores case or extra fields, contains() returns true whenever compare == 0, even if equals() is false.
Library declarations
Java
// java.util.TreeSet<E>
public boolean contains(Object o)
// Declared in Set<E> and Collection<E>
Parameters
Parameter
Description
o (Object)
The element to look for. Must be comparable with the set's elements.
Return Value
Return Value
Description
true
An element comparing equal (result 0) exists in the set.
Type mismatch caught at runtime. Because contains(Object) accepts any object, passing "443" compiles and fails when compared with Integer.
Fix the argument type. Always search a TreeSet<Integer> with an Integer (or int) rather than a String.
Frequently Asked Questions
It runs in O(log n) time by searching the balanced red-black tree rather than scanning every element.
It uses compareTo() or the custom Comparator returning 0, not equals().
Under natural ordering, contains(null) throws NullPointerException. Only a null-friendly Comparator allows null lookups.
Because the signature is contains(Object o) for Collection compatibility. At runtime, comparing a String with stored Integers throws ClassCastException.
It returns false rather than throwing an exception, even when the element exists in the backing TreeSet.