1. Introduction

TreeSet is an implementation of the SortedSet interface in Java, which uses a Red-Black tree as its backend. It ensures that the elements are stored in ascending order. Furthermore, TreeSet doesn’t permit the addition of null elements and duplicate values are automatically discarded. In this post, we will delve into the CRUD (Create, Read, Update, Delete) operations applicable to a TreeSet.

2. Program Steps

1. Initialize a TreeSet.

2. Populate the TreeSet with elements (Create).

3. Check if a specific element exists within the TreeSet (Read).

4. For the Update operation, since duplicates are not permitted in a TreeSet, we’ll first eliminate an old element and then append a new one.

5. Erase elements from the TreeSet.

6. Exhibit the final state of the TreeSet.

3. Code Program

import java.util.TreeSet;

public class TreeSetCRUDExample {
    public static void main(String[] args) {
        // 1. Initialize a TreeSet
        TreeSet<Integer> numbers = new TreeSet<>();

        // 2. Populate the TreeSet with elements (Create)
        numbers.add(3);
        numbers.add(1);
        numbers.add(4);
        System.out.println("After adding elements: " + numbers);

        // 3. Check if a specific element exists within the TreeSet (Read)
        boolean hasTwo = numbers.contains(2);
        System.out.println("Contains 2? " + hasTwo);

        // 4. Update operation: remove an element and append a new one
        numbers.remove(1);
        numbers.add(2);
        System.out.println("After updating elements: " + numbers);

        // 5. Erase elements from the TreeSet
        numbers.remove(3);
        System.out.println("After deleting 3: " + numbers);

        // 6. Exhibit the final state of the TreeSet
        System.out.println("Resultant TreeSet: " + numbers);
    }
}

Output:

After adding elements: [1, 3, 4]
Contains 2? false
After updating elements: [2, 3, 4]
After deleting 3: [2, 4]
Resultant TreeSet: [2, 4]

4. Step By Step Explanation

1. We begin by establishing an empty TreeSet of Integers.

2. With the help of the add method, three numbers are added. The TreeSet inherently sorts them.

3. To determine the presence of a specific item in the set, the contains method is employed.

4. An old element is deleted using the remove method, and then a new one is added with the add method, illustrating the Update process.

5. The remove method facilitates the deletion of elements.

6. The status of the TreeSet is displayed at various intervals to track the changes.

This guide provides a concise overview of the fundamental CRUD operations on a TreeSet in Java, emphasizing its innate sorting feature.