TreeSet contains(Object o) method in java

Let’s learn TreeSet contains(Object o) method in java.

TreeSet contains(Object o) method in java

contains(Object o) method of TreeSet class returns true if this set contains the specified element.

More formally, returns true if and only if this set contains an element e such that Objects.equals(o, e).

Syntax:

public boolean contains(Object o)

Parameters:

o object to be checked for containment in this set.

Throws:

ClassCastException – if the specified object cannot be compared with the elements currently in the set.

NullPointerException – if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

Also read – TreeSet in java

Now let’s see example on TreeSet contains(Object o) method.

import java.util.TreeSet;
public class TreeSetContainsObjectMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("mango");
      ts.add("grapes");
      ts.add("apple");
      ts.add("banana");
      ts.add("orange");
      ts.add("pineapple");
      System.out.println("TreeSet: " + ts);
      // check for "apple"
      System.out.println("Does TreeSet contains 'apple'? " + ts.contains("apple"));
      // check for "grapes"
      System.out.println("Does TreeSet contains 'grapes'? " + ts.contains("grapes"));
      // check for "red"
      System.out.println("Does TreeSet contains 'red'? " + ts.contains("red"));
   }
}


Output:

TreeSet: [apple, banana, grapes, mango, orange, pineapple]
Does TreeSet contains ‘apple’? true
Does TreeSet contains ‘grapes’? true
Does TreeSet contains ‘red’? false