Press "Enter" to skip to content

HashSet contains() Method in Java

The contains(Element e) method of HashSet checks if the HashSet contains the specified element or not. It returns true if the HashSet contains the specified element otherwise it returns false.

Syntax

boolean contains(Element e)

Parameters

e is the element whose presence in this HashSet is to be checked.
Freshers Placement

Return Value

It returns true if the HashSet contains the specified element otherwise it returns false.

Program 1

import java.util.HashSet;

public class HashSetContainsExample {

	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("Does set contains 20: " + set.contains(20));
		System.out.println("Does set contains 90: " + set.contains(90));
	}
}

Output

Set elements : [50, 20, 40, 10, 30]
Does set contains 20: true
Does set contains 90: false

Be First to Comment

Leave a Reply

Your email address will not be published.