1. Introduction
HashSet is a part of Java’s collection framework and is present in the java.util package. It implements the Set interface and does not allow duplicate elements. It doesn’t guarantee any order of its elements. In this tutorial, we will explore the CRUD (Create, Read, Update, Delete) operations that can be performed on a HashSet.
2. Program Steps
1. Initialize a HashSet.
2. Add elements to the HashSet (Create).
3. Verify if an element is present (Read).
4. As elements are unique in a HashSet, we’ll remove an element and add a new one for the Update operation.
5. Delete elements from the HashSet.
6. Display the resultant HashSet.
3. Code Program
import java.util.HashSet;
public class HashSetCRUDExample {
public static void main(String[] args) {
// 1. Initialize a HashSet
HashSet<String> colors = new HashSet<>();
// 2. Add elements to the HashSet (Create)
colors.add("Red");
colors.add("Blue");
colors.add("Green");
System.out.println("After adding elements: " + colors);
// 3. Verify if an element is present (Read)
boolean hasRed = colors.contains("Red");
System.out.println("Contains Red? " + hasRed);
// 4. Update operation: remove an element and add a new one
colors.remove("Blue");
colors.add("Yellow");
System.out.println("After updating elements: " + colors);
// 5. Delete elements from the HashSet
colors.remove("Green");
System.out.println("After deleting Green: " + colors);
// 6. Display the resultant HashSet
System.out.println("Resultant HashSet: " + colors);
}
}
Output:
After adding elements: [Red, Green, Blue] Contains Red? true After updating elements: [Red, Yellow, Green] After deleting Green: [Red, Yellow] Resultant HashSet: [Red, Yellow]
4. Step By Step Explanation
1. An empty HashSet named colors is initialized.
2. Using the add method, we introduce three colors to our set.
3. With the contains method, we can check if a certain item is present in the set.
4. Since HashSet doesn't support duplicates, updating requires removing an old item using remove and then introducing a new one with add.
5. The remove method is also employed to delete an element from the set.
6. At various stages, we display the state of the HashSet to track the changes.
This example showcases the fundamental CRUD operations on a HashSet in Java, emphasizing its unique characteristics.