Java TreeSet clear() remove() Methods Tutorial

In this section, we will learn what the TreeSet clear() and remove() methods are and how to use them in Java.

What is Java TreeSet clear() Method?

The Java TreeSet clear() method is used to remove the entire elements of a TreeSet object.

After calling this method on a TreeSet object, its size becomes 0.

Java clear() Method Syntax:

public void clear();

clear() Method Parameters:

The method does not take an argument.

clear() Method Return Value:

The return value of this method is void.

clear() Method Exceptions:

The method does not throw an exception.

Example: using TreeSet clear() method

import java.util.TreeSet; 
class Main{
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(1);
        ts.add(2);
        ts.add(3);
        ts.add(0);
        ts.add(10);
        ts.add(30);

        ts.clear();
        System.out.println("Is this list empty?: "+ts.isEmpty());
    }
}

Output:

Is this list empty?: true

What is Java TreeSet remove() Method?

The Java TreeSset remove() method is used to remove an element from a TreeSet object.

Java remove() Method Syntax:

public boolean remove(Object o)

remove() Method Parameters:

The method takes one argument and that is the element we want to remove from the target TreeSet object.

remove() Method Return Value:

The return value of this method is of boolean type.

If the target TreeSet object had the element we’ve set as the argument of the method and got removed because of calling the method, then the return value of this method becomes true.

Otherwise, the return value of this method will be false.

remove() Method Exceptions:

The method might throw two types of exceptions:

ClassCastException: We get this exception if the element in the argument is of incompatible type compared to the elements in the target TreeSet object.

NullPointerException: we get this exception if we put a null value as the argument of this method.

Example: using TreeSet remove() method

import java.util.TreeSet; 
class Main{
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(1);
        ts.add(2);
        ts.add(3);
        ts.add(0);
        ts.add(10);
        ts.add(30);

        ts.remove(30);
        for (int i: ts){
            System.out.println(i);
        }
    }
}

Output:

1

2

3

0

10

As you can see, we’ve called the remove() method to remove the value 30 from the set. Now this method searched the TreeSet object to find this method and so it got removed from the set.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies