Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashSet contains() Method

Java HashSet contains() Method

Java HashSet Java HashSet


contains() The method is in Java's HashSet is a commonly used method provided by the class, used to check whether the collection contains the specified element. The method returns a boolean value indicating whether the element exists.

Method Syntax

boolean

contains

(

Object

o

)

Method parameters

Parameters Type Description
o Object the element to find in the collection

Return Value

Return value type Description
boolean returns true if the collection contains the specified element, otherwise returns false

Method Principle

HashSet 's contains() The underlying implementation of the method relies on the hash table data structure:

  1. First, compute the hash code of the passed object
  2. Locate the corresponding position (bucket) in the hash table based on the hash code
  3. In this position (bucket), check whether there is an equal object (using equals() method to compare)

Usage examples

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 override hashCode() and equals() method in the component:

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 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

HashSet 's contains() method usually has O(1) time complexity because it is based on hash table implementation. But in the worst case (all elements hash-collide), the time complexity degrades to O(n).


7. Notes

  1. null Value Handling:HashSet allows containing one null element, you can use contains(null) to check
  2. Object Equality: When determining whether an object is contained, it relies on equals() method rather than the == operator
  3. Hash Collision: A good hashCode() implementation can reduce hash collisions and improve performance
  4. Concurrent Access:HashSet is not thread-safe; using it in a multi-threaded environment requires attention to synchronization issues

Frequently Asked Questions

Why does the contains() method sometimes return incorrect results?

This is usually because hashCode() and equals() method was not correctly overridden. Two logically equal objects must return the same hash code, and equals() method should return true.

What is the difference between the contains() method and the containsAll() method?

How to improve the performance of the contains() method?

  1. Ensure the custom object's hashCode() method is well implemented to reduce 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