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 LinkedHashSet here.

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 LinkedHashSet class.

  • In line number 4: We created a new LinkedHashSet object with the name set.

  • From lines number 5 to 7: We added three elements (1,2,3) to the set object using the add method.

  • In line number 10: We used the contains method to check if the element 3 is present in the set. The element 3 is present in the set, so true is returned.

  • In line number 10: We used the contains method to check if the element 4 is present in the set. The element 4 is not present in the set, so false is returned.

Free Resources