TreeSet contains(Object) in Java

contains(Object): This method is available in java.util.TreeSet class of Java.

Syntax:

boolean java.util.TreeSet.contains(Object o)

This method takes one argument. This method returns true if this set contains the specified element.

Parameters: One parameter is required for this method.

o: object to be checked for containment in this set.

Returns: true if this set contains the specified element.

Throws:

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

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

Approach 1: When no exception

Java

import java.util.TreeSet;

public class TreeSetcontains {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        treeSet.add("Hello");
        treeSet.add("Java");
        treeSet.add("Program");
        treeSet.add("C++");

        Object o = "Java";

        System.out.println(treeSet.contains(o));

    }
}

Output:

true


Approach 2: NullPointerException 

Java

import java.util.TreeSet;

public class TreeSetcontains {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        treeSet.add("Hello");
        treeSet.add("Java");
        treeSet.add("Program");
        treeSet.add("C++");

        Object o = null;

        System.out.println(treeSet.contains(o));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.TreeMap.getEntry(TreeMap.java:345) at java.base/java.util.TreeMap.containsKey(TreeMap.java:233) at java.base/java.util.TreeSet.contains(TreeSet.java:234)


No comments:

Post a Comment