1. Introduction

A HashSet is a collection of items where every item is unique, and it is found in the java.util package. You can use its add method to add elements to it. The add method adds the specified element to the set if it is not already present. If the set already contains the element, the call leaves the set unchanged and returns false.

2. Program Steps

1. Create a HashSet.

2. Add elements to the HashSet using the add method.

3. Print the HashSet and the result of the add method to the console.

3. Code Program

import java.util.HashSet;

public class HashSetExample {

    public static void main(String[] args) {

        // Step 1: Create a HashSet
        HashSet<String> fruits = new HashSet<>();

        // Step 2: Add elements to the HashSet
        boolean isAdded1 = fruits.add("Apple");
        boolean isAdded2 = fruits.add("Banana");
        boolean isAdded3 = fruits.add("Apple");

        // Step 3: Print the HashSet and the result of the add method
        System.out.println("HashSet: " + fruits);
        System.out.println("Was Apple added the first time? " + isAdded1);
        System.out.println("Was Banana added? " + isAdded2);
        System.out.println("Was Apple added the second time? " + isAdded3);
    }
}

Output:

HashSet: [Banana, Apple]
Was Apple added the first time? true
Was Banana added? true
Was Apple added the second time? false

4. Step By Step Explanation

Step 1: A HashSet named fruits is created.

Step 2: Elements are added to the HashSet using the add method. The add method returns true if the element is added successfully, and false if the element is already present in the HashSet.

Step 3: The HashSet and the result of the add method are printed to the console. As seen in the output, the HashSet does not allow duplicate elements, and the add method returns false when trying to add a duplicate element.