TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
This class provides numerous methods of which let us discuss contains() method of TreeSet class present inside java.util package is used to check if a specific element is present in the TreeSet or not. So basically it is used to check if a TreeSet contains any particular element.
Syntax:
Tree_Set.contains(Object element)
Parameters: The type of TreeSet. This is the element that needs to be checked if it is present in the TreeSet or not.
Return Value: A boolean value, true if the element is present in the set else it returns false.
Exceptions: It throws two types of exceptions listed below as follows:
- NullPointerException: If the specified element is null
- ClassCastException: If the specified element cannot be compared with the elements that currently exist in the set.
Tip: As we do know treeSet uses natural ordering and its comparator does not permit the null elements hence forth NullPointerException arises into play.
Example
Java
// Java Program to Illustrate contains() method // of TreeSet class // Importing required classes import java.io.*; import java.util.TreeSet; // Main class public class GFG { // Main driver method public static void main(String args[]) { // Creating an empty TreeSet of string type TreeSet<String> tree = new TreeSet<String>(); // Adding elements in TreeSet // Using add() method to tree.add( "Welcome" ); tree.add( "To" ); tree.add( "Geeks" ); tree.add( "4" ); tree.add( "Geeks" ); tree.add( "TreeSet" ); // Displaying the TreeSet System.out.println( "TreeSet: " + tree); // Use-case 1 // Check for specific element in the above TreeSet // object using contains() method of TreeSet class // Printing a boolean value System.out.println( "Does the Set contains 'TreeSet'? " + tree.contains( "TreeSet" )); // Use-case 2 // Check for specific element in the above TreeSet // object Say custom element be "4" System.out.println( "Does the Set contains '4'? " + tree.contains( "4" )); // Use-case 3 // Check if the list contains "No" System.out.println( "Does the Set contains 'No'? " + tree.contains( "No" )); } } |
TreeSet: [4, Geeks, To, TreeSet, Welcome] Does the Set contains 'TreeSet'? true Does the Set contains '4'? true Does the Set contains 'No'? false
Output Explanation:
As we inserted elements in TreeSet {“Welcome”, “To”, “Geeks”, “4”, “Geeks”, “TreeSet”} then we checks for a specific elements bypassing element as an argument to contains() method which we now returns boolean true if present else boolean false. The key point to remember is in java we only have true-false in boolean value nor do 0-1, take this note with you geeks.