HashSet implements the Set interface and inherits the AbstratSet class in Java that uses a HashTable for storage. HashSet applies the random order of the elements. Here, In this post, we will see an example on how to create a HashSet in java and how to iterates its data.

Simplest Presentation of Java HashSet Click To Tweet

Points to remember:

  1. HashSet elements would get returned in any random order.
  2. Java HashSet won’t return duplicate elements as If there is a duplicate element in the HashSet then the old value would be overwritten.
  3. Java HashSet is non-synchronized.
  4. HashSet allows null values.



Note: In below example 1, we are creating HashSet of type Integer and in example 2, it’s of String.

Example 1


Output 1:


Note: it could come to a different order for everyone.


Example 2


Output 2:



If you like this post, please check out my other similar posts:

HashTable in Java with Example



     Hashtable Javadoc