HashSet size() Method in Java

Published by user on

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

Syntax

int size()

Parameters

It does not take any parameter 

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 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
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *