In this section, we will learn what the TreeSet contains() method is and how to use it in Java.
What is Java TreeSet contains() Method?
The Java TreeSet contains() method is used to check and see if a TreeSet object has a specific element in its body.
Java contains() Method Syntax:
public boolean contains(Object o)
contains() Method Parameters:
The method takes one argument and that is the element we want to search a TreeSet object for.
contains() Method Return Value:
The return value of this method is of type boolean.
If the target list had the specified element in its body, then the return value of this method becomes true. Otherwise, the value false will return instead.
contains() Method Exceptions:
The method might throw two types of exceptions:
- NullPointerException: we get this exception if the argument of this method is null.
- ClassCastException: we get this exception if the argument datatype is of incompatible type compared to the data type of the elements in the target TreeSet object.
Example: using TreeSet contains() method
import java.util.TreeSet; class Main{ public static void main(String[] args) { TreeSet<Integer> ts = new TreeSet<>(); ts.add(1); ts.add(2); ts.add(3); ts.add(0); ts.add(10); ts.add(30); System.out.println(ts.contains(30)); } }
Output:
true