Java TreeSet clear() Method Example

The clear() method of java.util.TreeSet class will remove all the content of the TreeSet

Signature

public void clear()

This method removes all of the elements from the TreeSet.

Example

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

import java.util.TreeSet;

public class ClearMethodTreeSetExample 
{   
    public static void main(String args[])
    {
        // Create TreeSet object
        TreeSet treeSet1 = new TreeSet();
                        
        //adding elements to TreeSet using add()
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        
        //Printing the elements of the TreeSet1
        System.out.println("**Elements of the TreeSet1 before clear**");
        System.out.println("Size of the treeset : "+treeSet1.size());
        for(String val : treeSet1)
        {
                System.out.println(val);
        }
        
        treeSet1.clear();
        
        //Printing the elements of the TreeSet1
        System.out.println("**Elements of the TreeSet1 after clear**");
        System.out.println("Size of the treeset : "+treeSet1.size());
        for(String val : treeSet1)
        {
                System.out.println(val);
        }
    }
}

Output

**Elements of the TreeSet1 before clear**
Size of the treeset : 4
Element1
Element2
Element3
Element4
**Elements of the TreeSet1 after clear**
Size of the treeset : 0

Leave a Reply

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