HashSet in java

HashSet

In Java, a HashSet is a collection that stores elements in a hash table. It is implemented using a hash table and provides fast lookups and insertion, making it a good choice for storing large amounts of data when the order of the elements is not important.

A HashSet does not allow duplicate elements. If you try to add a duplicate element to a HashSet, it will simply ignore the insertion request and leave the set unchanged.

Here is an example of how to create and use a HashSet in Java

import java.util.HashSet;

public class Main {
  public static void main(String[] args) {
    // Create a HashSet
    HashSet<String> set = new HashSet<>();

    // Add elements to the set
    set.add("apple");
    set.add("banana");
    set.add("orange");

    // Try to add a duplicate element
    set.add("orange");

    // Check the size of the set
    System.out.println("Set size: " + set.size());  // Outputs "Set size: 3"

    // Check if an element is in the set
    System.out.println(set.contains("cherry"));  // Outputs is true
    System.out.println(set.contains("peach"));  // Outputs false
  }
}

In this example, we create a HashSet of strings and add three elements to it. Then we try to add a duplicate element ("orange"), but it is ignored because the HashSet does not allow duplicates. Finally, we check the size of the set and use the contains() method to check if certain elements are in the set.