Get size of HashSet in Java

In this tutorial, we will learn how to Get size of HashSet in Java.

HashSet in Java extends AbstractSet and implements Set interface which is backed by hash table.  It creates a collection that uses a hash table for storage. This class 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 null element. HashSet does not guarantee the order of its elements, because the process of hashing doesn’t usually lend itself to the creation of sorted sets.

In we want to calculate the size or no. of elements in HashSet, then this class in Java provides size() method to calculate the size. The size method returns the size or the no. of elements in HashSet. The syntax of size() method is:

Syntax of size() method:

Returns:
the number of elements in this set

Example:

Output:

 

Related posts

Leave a Comment