"HashSet and its operations" - A java implementation

 What is a HashSet?

            A HashSet is a collection of elements that uses a hash table for the storage. It is a built in class in java collections Framework.

Features of HashSet:

  • ·       No specific order of storing the elements.
  • ·       The user can store a null element.
  • ·       Duplicate elements can be ignored automatically.

Let us create a HashSet with its operations in  java.

Steps to follow:

  • Using the built in class HashSet and create an object instance hSet.
  • Add(): It inserts the elements to the HashSet.
  • Contains():  It returns a Boolean value. If it is true, then the element is available in the set. Otherwise, it is not available in the HashSet.
  • Remove(): Deletes an element.
  • Iteration: use a for loop.
  • hSet.size(); This function returns the size of the HashSet.
  • clear(): The emtire Hashset is cleared using this function.
  • isEmpty(): it returns true when the Hashset is empty.

Program:

import java.util.HashSet;

public class HashSetEg1 {

    public static void main(String[] args) {

        HashSet<String> hSet = new HashSet<>();

        // Insert the elements to the HashSet by add() function

        hSet.add("Onion");

        hSet.add("Tomato");

        hSet.add("Potato");

        hSet.add("Carrot");

        hSet.add("Beans");

        hSet.add("Onion"); // it is a duplicate entry. but it is automatically ignored

        // To display the HashSet

        System.out.println("HashSet: " + hSet);

        // Search an element

        boolean containsIt = hSet.contains("Tomato");

        if(containsIt)

         System.out.println("Yes. The Hash set contains the Tomato");

        else

           System.out.println("Yes. The Hash set does not contain the Tomato");

      // Delete an element from the HashSet

        hSet.remove("Potato");

        System.out.println("HashSet after deleting Potato: " + hSet);

   // Looping and printing

        System.out.println("Print the HashSet:");

        for (String veggie : hSet) {

            System.out.println(veggie);

        }

        // let us find the size of Hash Set

        int size1 = hSet.size();

        System.out.println("The size of Hash Set is: " + size1);

        // Clear it all

        hSet.clear();

        if(hSet.isEmpty())

        System.out.println("HashSet is empty after clearing");

    }

}

Output:

C:\raji\blog>javac HashSetEg1.java

C:\raji\blog>java HashSetEg1

HashSet: [Potato, Carrot, Beans, Onion, Tomato]

Yes. The Hash set contains the Tomato

HashSet after deleting Potato: [Carrot, Beans, Onion, Tomato]

Print the HashSet:

Carrot

Beans

Onion

Tomato

The size of Hash Set is: 4

HashSet is empty after clearing

This is the way of creating a powerful HashSet and its operations in java. Keep coding!!!!

No comments:

Post a Comment