TreeSet add() method in java

Let’s learn TreeSet add() method in java.

TreeSet add() method in java

add(E e) method of TreeSet class adds the specified element to this set if it is not already present.

More formally, adds the specified element e to this set if the set contains no element e2 such that Objects.equals(e, e2).

If this set already contains the element, the call leaves the set unchanged and returns false.

Syntax:

public boolean add(E e)

Parameters:

e element to be added to this set.

Throws:

ClassCastException – if the specified object cannot be compared with the elements currently in this set.

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

Also read – TreeSet in java

Now let’s see example on TreeSet add() method.

import java.util.TreeSet;
public class TreeSetAddMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("yellow");
      ts.add("orange");
      ts.add("green");
      ts.add("red");
      ts.add("blue");
      ts.add("violet");
      System.out.println("TreeSet: " + ts);
   }
}


Output:

TreeSet: [blue, green, orange, red, violet, yellow]