Java HashSet is an implementation of Set interface. The HashSet class is backed by instance of HashMap. Java Set is a collection which allows only unique values.
The HashSet class does not guarantee the order of the elements. That means that the elements may not returned in the same order in which they were inserted into the HashSet.
The HashSet class allows null element, but since it is a collection of unique values, only one null element can be inserted into HashSet.
The add method is used to insert the elements into the HashSet object. The contains method is used to check if the element exists in the HashSet. The iterator method is used to get iterator for the HashSet which gives values contained in the HashSet object while iterating over it.
The HashSet implementation is not synchronized. That means if multiple threads are trying to modify the HashSet concurrently, the code must do synchronization explicitly. However, you can get the synchronized Set from the HashSet object using the synchronizedSet method of the Collections class.
Since the HashSet class is backed by HashMap, it offers constant time performance for basic operations like add, remove, contains and size.
Below given are some of the Java HashSet examples which shows how to use HashSet in Java.