Home >Java >javaTutorial >Does ArrayList's `contains()` Method Use Object Equality or Reference Equality?

Does ArrayList's `contains()` Method Use Object Equality or Reference Equality?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 18:06:171006browse

Does ArrayList's `contains()` Method Use Object Equality or Reference Equality?

Understanding Object Comparison in ArrayList's contains() Method

The contains() method in ArrayList evaluates whether a given object exists within the list. When determining object equality, ArrayList utilizes the equals() method defined within the object's class.

Consider the following scenario: you create a Thing object with an integer value and add it to an ArrayList. If you subsequently create another Thing object with an identical value, will the contains() method identify them as equivalent?

Implementation Considerations

For the contains() method to return true, the equals() method within the Thing class must be implemented appropriately. In this case, the equals() method correctly compares the value instance variable between the objects, returning true if they are identical.

Conclusion

The contains() method in ArrayList delegates object comparison to the equals() method defined in the object's class. By implementing equals() to compare relevant instance variables, you can ensure that objects are correctly identified as equal or not in ArrayList operations.

The above is the detailed content of Does ArrayList's `contains()` Method Use Object Equality or Reference Equality?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn