The HashSet Class in java

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. HashSet is a generic class that has this declaration:

class HashSet<E>

Here, specifies the type of objects that the set will hold.

The advantage of hashing is that it allows the execution time of add( ), contains( ), remove( ), and size( ) to remain constant even for large sets.

The following constructors are defined:

HashSet( )

HashSet(Collection<? extends E> c)

HashSet(int capacity)

HashSet(int capacity, float fillRatio)

The first form constructs a default hash set. The second form initializes the hash set by using the elements of c. The third form initializes the capacity of the hash set to capacity. (The default capacity is 16.) The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments. The fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For constructors that do not take a fill ratio, 0.75 is used.

HashSet does not define any additional methods beyond those provided by its superclasses and interfaces.

Table of Contents

Demonstrate HashSet

import java.util.*;

class HashSetDemo {

public static void main(String args[]) { // Create a hash set.

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

//Add elements to the hash set. hs.add("B");

hs.add("A");

hs.add("D");

hs.add("E");

hs.add("C");

hs.add("F");

System.out.println(hs);

}

}

Output

[D, A, F, C, B, E]

Leave a Comment