Java HashSet contains() Method
contains()The method is a commonly used method in JavaHashSetprovided by the HashSet class, used to check whether the collection contains the specified element. This method returns a boolean value indicating whether the element exists.
Method Syntax
Method Parameters
| Parameter | Type | Description |
|---|---|---|
| o | Object | The element to search for in the collection |
Return Value
| Return Value Type | Description |
|---|---|
| boolean | Returns true if the collection contains the specified element; otherwise, returns false |
How the Method Works
HashSetofcontains()The underlying implementation of the method relies on a hash table data structure:
- First, calculate the hash code of the passed-in object
- Locate the corresponding position (bucket) in the hash table based on the hash code
- Search that position (bucket) for an equal object (using
equals()the equals() method for comparison)
Usage Example
Basic Usage
Example
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> fruits = new HashSet<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Check whether the element exists
System.out.println("Contains Apple? " + fruits.contains("Apple")); // true
System.out.println("Contains Mango? " + fruits.contains("Mango")); // false
}
}
Custom Objects
When using custom objects, you need to correctly overridehashCode()andequals()the hashCode() and equals() methods:
Example
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
// Must override the hashCode and equals methods
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return id == student.id;
}
}
public class CustomObjectExample {
public static void main(String[] args) {
HashSet<Student> students = new HashSet<>();
students.add(new Student(1, "Alice"));
students.add(new Student(2, "Bob"));
System.out.println("Contains Alice? " +
students.contains(new Student(1, "Alice"))); // true
}
}
Performance Considerations
HashSetofcontains()The method usually has O(1) time complexity because it is based on a hash table. However, in the worst case (when all elements have hash collisions), the time complexity degrades to O(n).
7. Notes
- Null Value Handling:
HashSetIt allows one null element; you can use contains()contains(null)to check for it - Object Equality: When determining whether an object is contained, it relies on the
equals()equals() method rather than the == operator - Hash Collision: A good
hashCode()hashCode() implementation can reduce hash collisions and improve performance - Concurrent Access:
HashSetNot thread-safe. In a multi-threaded environment, you need to pay attention to synchronization issues.
FAQ
Why does the contains() method sometimes return incorrect results?
This is usually because you did not correctly overridehashCode()andequals()the hashCode() and equals() methods. Two logically equal objects must return the same hash code, andequals()the equals() method should return true.
What is the difference between the contains() method and the containsAll() method?
contains(): Checks whether a single element existscontainsAll(): Checks whether all elements in the specified collection are included
How can I improve the performance of the contains() method?
- Ensure that the custom object's
hashCode()hashCode() and equals() method implementations are good, reducing hash collisions - For large collections, consider adjusting the initial capacity and load factor
- Use a more suitable data structure (such as TreeSet) if ordering is more important
Java HashSet