HashSet in Java

HashSet  Inherits from the abstract class AbstractSet and implements the java.util.Set. The HashSet class creates a collection of objects that uses a hash table for storage.

A hash table stores values by giving them a unique key to identify them. A key cannot be associated with two values, unlike HashMap.

Constructors

HashSet has four constructors:
  • HashSet(): Create an empty list with initial capacity 16.
  • HashSet(Collection c): Create a new set containing the items from collection c. The ability automatically increases when elements are added.
  • HashSet(int capaciteInit): Create an empty list of initial capacity  capaciteInit.
  • HashSet(int  capaciteInit, float loadFactor): Create an empty HashSet of initial capacity and loadFactor that should be between 0.0 and 1.0, it determines the size of the list before it is resized.

Methods

The list of methods apart from those inherited from the parent classes:
  • add(E e): add an element;
  • remove(Object o): delete an element;
  • clear(): delete all elements of HashSet;
  • contains(Object o): returns true if the object you are looking for exists otherwise false;
  • isEmpty(): returns true if the list is empty;
  • size(): returns the size;
  • iterator(): returns an object of type Iterator.

Example

import java.util.HashSet; 

public class ExampleHashSet {

public static void main(String[] args) {
HashSet< String> hset = new HashSet< String> ();
 //add elements
hset.add("hotel");
hset.add("motel");
hset.add("fondouk");
hset.add("spring");

System.out.println(hset.size());
//delete the motel
hset.remove("motel");
//test existence
System.out.println(hset.contains("motel"));
//check if set is empty
System.out.println(hset.isEmpty());

//browse HashSet
for(String value:
hset)
 System.out.println(value); 
}
}