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.
The important points about Java HashSet class are:
Difference between List and Set
A list can contain duplicate elements whereas Set contains unique elements only.
Hierarchy of HashSet class
The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.
HashSet class declaration
Let's see the declaration for java.util.HashSet class.
Constructors of Java HashSet class
Methods of Java HashSet class
Various methods of Java HashSet class are as follows:
Java HashSet Example
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
Five One Four Two Three
Java HashSet example ignoring duplicate elements
In this example, we see that HashSet doesn't allow duplicate elements.
Ajay Vijay Ravi
Java HashSet example to remove elements
Here, we see different ways to remove an element.
An initial list of elements: [Vijay, Ravi, Arun, Sumit] After invoking remove(object) method: [Vijay, Arun, Sumit] Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay] After invoking removeAll() method: [Vijay, Arun, Sumit] After invoking removeIf() method: [Arun, Sumit] After invoking clear() method: 
Java HashSet from another Collection
Vijay Ravi Gaurav Ajay
Java HashSet Example: Book
Let's see a HashSet example where we are adding books to set and printing all the books.
101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications & Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6
You may also like:Working of HashSet in Java
Next TopicJava LinkedHashSet class