Guide to HashSet Class

In this guide, we’re going to take a look at HashSet class from Java Collections Framework.

We will learn all the APIs that HashSet implementation offers.

HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

HashSet implementation is not synchronized - If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.

Example:

Set s =Collections.synchronizedSet(newHashSet(...));

This guide covers important HashSet implementation API with examples. All the APIs referred from HashSet JavaDoc.

What Will We Learn?

Set interface Overview

HashSet class Overview

Create a HashSet and Adding new Elements Example

add() method

addAll() method

HashSet remove API's with Example

remove(Object o)

removeAll(Collection<?> c)

removeIf(Predicate<? super Integer> filter)

clear()

Demonstration of How the Set contains duplicates and null values?

HashSet Bulk Operations API's with Examples

addAll()

retainAll()

containsAll()

removeAll()

Iterating over a HashSet

iterator()

Advance for() loop

forEachRemaining()

forEach()

HashSet with User-defined objects

How to make HashSet thread safe?

1. Set interface Overview

The Set interface contains only methods inherited from Collection interface and adds the restriction that duplicate elements are prohibited.

A Set that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

As implied by its name, this interface models the mathematical set abstraction.

Set does not guarantee an insertion order.

2. HashSet class Overview

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.

9. How to make HashSet thread safe?

This class implementation is not synchronized so it is not thread-safe. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.HashSet must be synchronized externally.Example :