Java TreeSet size() isEmpty() Methods Tutorial

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

What is Java TreeSet size() Method?

The Java TreeSet size() method is used to return the current number of elements in a TreeSet object.

Java TreeSet size() Method Syntax:

public int size()

size() Method Parameters:

The method does not take an argument.

size() Method Return Value:

The return value of this method is of type Integer and is equal to the current number of elements in a TreeSet object.

size() Method Exceptions:

The method does not throw an exception.

Example: using TreeSet size() 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);

        System.out.println(ts.size());
    }
}

Output:

6

What is Java TreeSet isEmpty() Method?

The Java TreeSet isEmpty() method is used to see if there’s an element in a TreeSet object or not.

If there’s at least one element in the target TreeSet object, the return value of this method will be false, meaning the object is not empty. Otherwise, the value true will return (which means there is at least one element in that object).

Java TreeSet isEmpty() Method Syntax:

public boolean isEmpty()

isEmpty() Method Parameters:

The method does not take an argument.

isEmpty() Method Return Value:

The return value of this method is of type Boolean.

If a TreeSet object was empty (no element in it) then the return value of this method becomes true.

Otherwise, the value false will return instead.

isEmpty() Method Exceptions:

The method does not throw an exception.

Example: using TreeSet isEmpty() 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);

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

Output:

Is this list empty?: false

Leave a Reply