Java TreeSet - contains() Method
The java.util.TreeSet.contains() method is used to check whether the set contains the specified element or not. The method returns true if the set contains the specified element, else returns false.
Syntax
public boolean contains(Object obj)
Parameters
obj |
Specify the object to be checked for containment in this set. |
Return Value
Returns true if this set contains the specified element.
Exception
- Throws ClassCastException, if the specified object cannot be compared with the elements currently in the set.
- Throws NullPointerException, if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.
Example:
In the example below, the java.util.TreeSet.contains() method is used to check the presence of specified element in the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating treeset TreeSet<Integer> MySet = new TreeSet<Integer>(); //populating the set MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); //checking the presence of elements for(int i = 5; i <= 20; i += 5) { if(MySet.contains(i)) System.out.println(i +" is present in MySet."); else System.out.println(i +" is NOT present in MySet."); } } }
The output of the above code will be:
5 is NOT present in MySet. 10 is present in MySet. 15 is NOT present in MySet. 20 is present in MySet.
❮ Java.util - TreeSet