1. Introduction
In Java, a HashSet is part of the Collections Framework and is used to store unique elements. The contains method in HashSet is employed to check whether a particular element is present in the set. It returns true if the element is found, otherwise false.
2. Program Steps
1. Initialize a HashSet and populate it with some elements.
2. Utilize the contains method to verify if a specific element is in the HashSet.
3. Print the result to the console.
3. Code Program
import java.util.HashSet;
public class HashSetContains {
public static void main(String[] args) {
// Step 1: Initialize a HashSet and populate it with some elements
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Utilize the contains method to verify if a specific element is in the HashSet
boolean containsBanana = fruits.contains("Banana");
// Step 3: Print the result to the console
System.out.println("Does the HashSet contain Banana? " + containsBanana);
}
}
Output:
Does the HashSet contain Banana? true
4. Step By Step Explanation
Step 1: A HashSet named fruits is initialized and populated with several elements.
Step 2: The contains method is utilized to check whether the element "Banana" is present in the HashSet. It returns true, indicating that the element exists in the set.
Step 3: The outcome of the contains method is printed to the console, confirming that "Banana" is indeed present in the HashSet.