HashSet basics

The HashSet class is a general set class that implements the Set interface. The elements are stored in a hash table that allows quick access.

It is generally used when no mapping of keys to pairs of values is required, unlike the HashMap.

Syntax

import java.util.HashSet;

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

HashSet Example

This code defines a class named “HashSet” which creates an instance of the java.util.HashSet class and performs some operations on it.

The class creates a HashSet object set of type String and adds 4 elements to it: “First”, “Second”, “Third”, and “Fourth”. Then, it checks if the set is empty using isEmpty() method and gets the size of the set using size() method. It also checks if the set contains an element “Third” using contains("Third") method and removes an element “Fourth” using the remove("Fourth") method.

The code then uses an enhanced for loop to output all the elements in the set and an iterator to output the elements in the set.

In summary, this code demonstrates how to create and use a HashSet in Java.

import java.util.HashSet;
import java.util.Iterator;

class HashSet {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<String>();
		set.add("First");
		set.add("Second");
		set.add("Third");
		set.add("Fourth");

		boolean isEmpty = set.isEmpty();
		int size = set.size();
		boolean containsEntry = set.contains("Third");
		set.remove("Fourth");

		System.out.println("isEmpty: " + isEmpty);
		System.out.println("size: " + size);
		System.out.println("containsEntry: " + containsEntry);

		// output elements using enhanced for loop
		for (String s : set) {
			System.out.println(s);
		}

		// output elements using iterator
		System.out.println("\nIterator output");
		Iterator<String> iter = set.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}
}
Output
isEmpty: false
size: 4
containsEntry: true
Second
Third
First

Iterator output
Second
Third
First