Java TreeSet add(E e) Method Example

In this tutorial we will learn about add(E e) method of java.util.TreeSet class. This method Adds the specified element to the set if it is not already present.

Signature

public boolean add(E e)

This method adds element to the set if not present, if the insertion is successful it will return true. Throws  java.lang.ClassCastException if the specified object cannot be compared with the elements currently in this set and java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

Example

The following example shows the usage of java.util.TreeSet.add(e) method.

import java.util.TreeSet;

public class AddMethodTreeSetExample 
{
    public static void main(String args[])
    {
        //Create TreeSet object treeSet1
        TreeSet treeSet1 = new TreeSet();
        
        //add the elements to treeSet1 using add() method
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        
        boolean flag = treeSet1.add("Element5"); 
        System.out.println("Was the insertion of \"Element5\" successfull ?? : "+flag);
        
        //Printing the elements of the treeSet1
        System.out.println("**Elements of the TreeSet**");
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
        
        //Lets try to add a duplicate element to treeSet1
        flag = treeSet1.add("Element2");
        System.out.println("Was the insertion of \"Element2\" successfull ?? : "+flag);
        
        //Printing the elements of the treeSet1
        System.out.println("**Elements of the TreeSet**");
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
    }
}

Output

Was the insertion of "Element5" successful : true
**Elements of the TreeSet**
Element1
Element2
Element3
Element4
Element5
Was the insertion of "Element2" successful : false
**Elements of the TreeSet**
Element1
Element2
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *