In this guide, you will learn about the LinkedHashSet contains() method in Java programming and how to use it with an example.
1. LinkedHashSet contains() Method Overview
Definition:
The contains() method of the LinkedHashSet class in Java is used to check whether a specific element is present in the set or not. It returns true if the set contains the specified element, otherwise, it returns false.
Syntax:
public boolean contains(Object o)
Parameters:
- o: The element whose presence in this set is to be tested.
Key Points:
- The contains() method is used to check the presence of a single element in the LinkedHashSet.
- The method will return true if the specified element is found in the set; otherwise, it will return false.
- The method accepts any Object as its parameter.
- The contains() method works in constant time, O(1), for this implementation, making it efficient.
- If the object passed to contains() is not of the correct type or is null, the method will return false.
2. LinkedHashSet contains() Method Example
import java.util.LinkedHashSet;
public class LinkedHashSetContainsExample {
public static void main(String[] args) {
LinkedHashSet<String> fruitSet = new LinkedHashSet<>();
// Adding elements to the LinkedHashSet
fruitSet.add("Apple");
fruitSet.add("Banana");
fruitSet.add("Cherry");
// Printing the LinkedHashSet
System.out.println("LinkedHashSet: " + fruitSet);
// Checking the presence of elements
System.out.println("Contains Apple? " + fruitSet.contains("Apple"));
System.out.println("Contains Orange? " + fruitSet.contains("Orange"));
System.out.println("Contains null? " + fruitSet.contains(null));
}
}
Output:
LinkedHashSet: [Apple, Banana, Cherry] Contains Apple? true Contains Orange? false Contains null? false
Explanation:
In this example, we have a LinkedHashSet containing some elements.
We then use the contains() method to check the presence of various elements in the set, including a null value. The output demonstrates that the method accurately identifies whether the specified elements are present in the LinkedHashSet or not, returning true or false accordingly.
Comments
Post a Comment
Leave Comment