TreeSet add(String) in Java

add(String): This method is available in java.util.TreeSet class of Java.

Syntax:

boolean java.util.TreeSet.add(String e)

This method takes one argument. This method adds the specified element to this set if it is not already present.

Parameters: One parameter is required for this method.

e: the element to be added to this set.

Returns: true if this set did not already contain the specified element.

Throws:

1. ClassCastException - if the specified object cannot be compared with the elements currently in this 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 TreeSetadd {
    public static void main(String[] args) {

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

        System.out.println(treeSet.add("Hello"));
    }
}

Output:

true


Approach 2: NullPointerException 

Java

import java.util.TreeSet;

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

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

        System.out.println(treeSet.add(null));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:768) at java.base/java.util.TreeMap.put(TreeMap.java:777) at java.base/java.util.TreeMap.put(TreeMap.java:534) at java.base/java.util.TreeSet.add(TreeSet.java:255)


No comments:

Post a Comment