Java HashSet size() Method Example

The size() method of java.util.HashSet class will return us the actual size of the HashSet(Count of number of elements present in the HashSet).

Signature

public int size()

This method returns number of elements in this HashSet.

Example

The following example shows the usage of java.util.HashSet.size() method.

import java.util.HashSet;

public class SizeMethodHashSetExample {
	public static void main(String args[])
	{
		// create an empty HashSet
		HashSet<String> hashSet1 = new HashSet<String>();
		
		// use add() method to add elements to the HashSet
		hashSet1.add("Element1");
		hashSet1.add("Element2");
		hashSet1.add("Element3");
		hashSet1.add("Element4");
		hashSet1.add("Element5");
		
		//Getting the size of the HashSet
		System.out.println("Size of the HashSet is : \""+hashSet1.size()+"\"");
			
		//Printing the elements of the HashSet
		System.out.println("**Elements of the HashSet **");
		for(String temp:hashSet1)
		{
			System.out.println(temp);
		}
	}
}

Output

Size of the HashSet is : "5"
**Elements of the HashSet**
Element1
Element2
Element3
Element4
Element5

Leave a Reply

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