Home >Java >javaTutorial >How Does ArrayList's `contains()` Method Determine Object Equality?
Object Comparison in ArrayList: How contains() Determines Object Equality
When adding an object to an ArrayList, it's often assumed that the contains() method will evaluate objects based solely on their field values. However, the actual process is more nuanced than that.
In Java, the List interface, which ArrayList implements, defines the signature of the contains() method. According to the documentation, the method "returns true if and only if this list contains the specified element." But how does the list determine if two objects are the same?
The Role of equals()
The answer lies in the equals() method, which is defined in the Object class. This method is responsible for comparing two objects and determining if they represent the same value. When the contains() method is called, it internally calls the equals() method to determine if the specified object matches any of the objects in the list.
Custom equals() for Custom Objects
In your specific example, you define a custom equals() method in the Thing class. This is necessary because by default, the equals() method provided by Object compares object references, not the field values. Your implementation correctly compares the value field to determine if the two Thing objects are equal.
Assuming that the Thing class is implemented as shown, the contains() method will indeed return true when searching for an object that is identical to the one previously added to the basket list. This is because the equals() method returns true when the value fields of the two objects match.
Conclusion
In summary, the ArrayList's contains() method utilizes the equals() method to determine if two objects are equal. For custom object classes, you may need to override the equals() method to provide your own implementation based on the specific properties that define equality for your objects.
The above is the detailed content of How Does ArrayList's `contains()` Method Determine Object Equality?. For more information, please follow other related articles on the PHP Chinese website!