java.util.HashSet contains()
Description
The HashSet as majority of the Collection classes make use of Generics such that if we have declared our set like HashSet set = new HashSet() then the elements of inside our set is of type String. And we cannot insert different object type not unless its a subclass of the object declaration, otherwise a runtime error will be thrown.
The HashSet elements are unique, there would be no two identical elements that can exist.
Important notes for isEmpty() method:
- specified by contains in interface Collection<E>
- specified by contains in interface Set<E>
- overrides contains in class AbstractCollection<E>
Method Syntax
public boolean contains(Object o)
Method Argument
Data Type | Parameter | Description |
---|---|---|
Object | o | element whose presence in this set is to be tested |
Method Returns
The contains(Object o) method returns true if this set contains the specified element.
Compatibility
Requires Java 1.2 and up
Java HashSet contains() Example
Below is a java code demonstrates the use of contains() method of HashSet class. The example presented might be simple however it shows the behavior of the contains() method.
package com.javatutorialhq.java.examples; import static java.lang.System.*; import java.util.HashSet; import java.util.Scanner; /* * This example source code demonstrates the use of * contains() method of HashSet class */ public class HashSetContainsExample { public static void main(String[] args) { // get the HashMap object from the method init() HashSet studentSet = init(); // ask user input out.println("Enter student name:"); Scanner s = new Scanner(System.in); String name = s.nextLine(); s.close(); //check if the user input is in the student db if(studentSet.contains(name)){ out.println(name +" found on student list"); } else{ out.println(name +" name not on the student list"); } } private static HashSet init() { // declare the HashSet object HashSet studentSet = new HashSet<>(); // put contents to our HashMap studentSet.add("Shyra Travis"); studentSet.add("Sharon Wallace"); studentSet.add("Leo Batista"); return studentSet; } }
There are two methods created on the above example, main() and init. The main method calls the init() which initializes and assign values to a HashSet object. The main() method assign to a new HashSet object the returned object by the init() method. As you would have noticed we have used the Scanner class to get user input and then we check it on our current set if it is in there. The discussion on the use of scanner is out of scope however you can go to our scanner tutorial for more information.