Java HashSet size() Method Tutorial

In this section, we will learn what the HashSet size() method is and how to use it in Java.

What is Java HashSet size() Method?

The Java HashSet size() method is used to get the current number of elements in a HashSet object.

For example, if a HashSet object has 10 elements and we call this method upon that object, the value 10 will return.

Java HashSet size() Method Syntax:

public int size()

size() Method Parameters:

The method does not take an argument.

size() Method Return Value:

The return value of this method is of type Integer and is equal to the number of elements of the target HashSet object.

size() Method Exceptions:

The method does not throw an exception.

Example: using HashSet size() method

import java.util.HashSet; 
public class Main {

    public static void main(String[] args){
      HashSet<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      set.add(5);
      set.add(6);
      set.add(7);

      System.out.println("The size of the set before calling the clear() method: "+set.size());
      set.clear();
      System.out.println("The size of the set after claing the clear() method: "+set.size());
    }
}

Output:

The size of the set before calling the clear() method: 7

The size of the set after calling the clear() method: 0
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies