java hashset

java

In Java, a HashSet is a class that implements the Set interface and uses a hash table for storage. A Set is a collection that cannot contain duplicate elements, and it does not preserve the insertion order of the elements.

A HashSet is an efficient implementation of a Set, as it allows you to add, remove, and check for the presence of elements in the set in constant time, on average. This is achieved by using a hash function to map the elements to a set of indices in the underlying hash table, and by storing the elements in an unsorted manner.

Here is an example of how you can create and use a HashSet in Java:

import java.util.HashSet;

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

    // add some elements to the set
    set.add("apple");
    set.add("banana");
    set.add("cherry");

    // check if an element is in the set
    System.out.println("banana is in the set: " + set.contains("banana"));

    // remove an element from the set
    set.remove("cherry");

    // print the size of the set
    System.out.println("Size of the set: " + set.size());
  }
}

This will output the following:

banana is in the set: true
Size of the set: 2

In this example, we create a HashSet of strings, add some elements to it, check if an element is in the set, and remove an element from the set. We also print the size of the set to see how many elements it contains.

Note: The HashSet class is not synchronized, which means that multiple threads may access it concurrently without causing thread-safety issues. If you need a thread-safe Set implementation, you can use the java.util.Collections.synchronizedSet() method to wrap a HashSet in a thread-safe wrapper.