Java HashSet contains() Method Tutorial

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

What is Java HashSet contains() Method?

The Java HashSet contains() method is used to check and see if a HashSet object has an element in its body.

Java HashSet contains() Method Syntax:

public boolean contains(Object o)

contains() Method Parameters:

The method takes one argument and that is the element we want to check a HashSet object for.

contains() Method Return Value:

The return value of this method is of type boolean.

If the target HashSet object had the element we’ve set as the argument of this method, then the return value will be true.

Otherwise, the value false will return instead.

contains() Method Exceptions:

The method does not throw an exception.

Example: using HashSet contains() method

import java.util.HashSet; 
class Main{
    public static void main(String[] args) {
        HashSet<Integer> hash = new HashSet<>();


Output: true

Leave a Reply