What is the LinkedHashSet.contains method in Java?
LinkedHashSet is similar to HashSet, except that LinkedHashSet maintains the insertion order of elements, whereas HashSet does not.
Read more about
LinkedHashSethere.
The contains method can be used to check if an element is present in the LinkedHashSet object or not.
Syntax
public boolean contains(Object o)
Parameters
The argument for this method is the element that is to be checked to see whether or not it is contained within the LinkedHashSet object.
Return value
This method returns true if the passed element is present in the set. Otherwise, false is returned.
Code
import java.util.LinkedHashSet;class Contains {public static void main( String args[] ) {LinkedHashSet<Integer> set = new LinkedHashSet<>();set.add(1);set.add(2);set.add(3);System.out.println("The set is " + set);System.out.println("Calling set.contains(3). has element - " + set.contains(3));System.out.println("Calling set.contains(4). has element - " + set.contains(4));}}
Explanation
In the above code:
-
In line number 1: We imported the
LinkedHashSetclass. -
In line number 4: We created a new
LinkedHashSetobject with the nameset. -
From lines number 5 to 7: We added three elements (
1,2,3) to thesetobject using theaddmethod. -
In line number 10: We used the
containsmethod to check if the element3is present in theset. The element3is present in the set, sotrueis returned. -
In line number 10: We used the
containsmethod to check if the element4is present in theset. The element4is not present in the set, sofalseis returned.