Press "Enter" to skip to content

HashSet size() Method in Java

The size() method of HashSet returns the number of elements available in the HashSet.

Syntax

int size()

Parameters

It does not take any parameter 
Freshers Placement

Return Value

It returns the number of elements in the HashSet

Program 1

import java.util.HashSet;

public class HashSetSizeExample {

	public static void main(String[] args) {

		HashSet<Integer> set = new HashSet<>();
		set.add(10);
		set.add(20);
		set.add(30);
		set.add(40);
		set.add(50);

		System.out.println("Set elements: " + set);
		System.out.println("Number of elements in set: " + set.size());
	}
}

Output

Set elements: [50, 20, 40, 10, 30]
Number of elements in set: 5

Be First to Comment

Leave a Reply

Your email address will not be published.