Java Utility Library

Java TreeSet - add() Method



The java.util.TreeSet.add() method is used to add a new element in the set. The element is added if it is not already present in the set.

Syntax

public boolean add(E element)

Here, E is the type of element maintained by the container.


Parameters

element Specify element which need to be added in the set.

Return Value

Returns true if the element is successfully added, else returns false.

Exception

  • Throws ClassCastException, if the specified object cannot be compared with the elements currently in this 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.add() method is used to add new element in the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing the set
    System.out.println("MySet contains: " + MySet);   
  }
}

The output of the above code will be:

MySet contains: [10, 20, 30, 40]

❮ Java.util - TreeSet