Java HashSet contains() Method

Java HashSet Java HashSet


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

boolean contains(Object o)

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:

  1. First, calculate the hash code of the passed-in object
  2. Locate the corresponding position (bucket) in the hash table based on the hash code
  3. Search that position (bucket) for an equal object (usingequals()the equals() method for comparison)

Usage Example

Basic Usage

Example

import java.util.HashSet;

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

import java.util.HashSet;

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

  1. Null Value Handling:HashSetIt allows one null element; you can use contains()contains(null)to check for it
  2. Object Equality: When determining whether an object is contained, it relies on theequals()equals() method rather than the == operator
  3. Hash Collision: A goodhashCode()hashCode() implementation can reduce hash collisions and improve performance
  4. 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 exists
  • containsAll(): Checks whether all elements in the specified collection are included

How can I improve the performance of the contains() method?

  1. Ensure that the custom object'shashCode()hashCode() and equals() method implementations are good, reducing hash collisions
  2. For large collections, consider adjusting the initial capacity and load factor
  3. Use a more suitable data structure (such as TreeSet) if ordering is more important

Java HashSet Java HashSet

Other Extensions