Set is a collection that cannot contain duplicate elements.
HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance). That is, it stores its elements in a hash table.
HashSet has best performance among all the implementations. But it makes no guarantees concerning the order of iteration; in particular, it does not guarantee that the order will remain constant over time.
HashSet class permits the
null element. It must be noted that a set may contain at most one null element (not more than one because no duplicates are allowed in a set).
Java provides the HashSet class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
The following example illustrates the HashSet class.
As you can see from the above output, there are no duplicate elements in the HashSet. Also, HashSet didn’t preserve the insertion order of the elements.
The above program showed the use of some of the common methods of the HashSet class. For a complete list of all the available methods, refer the official docs.
Now since you know how to use the HashSet class, check out other implementations of the Set interface: