Home >Java >javaTutorial >How Does ArrayList's `contains()` Method Evaluate Object Equality?
ArrayList's Evaluation of Objects in the contains() Method
An ArrayList is a highly utilized data structure in Java. One of its crucial methods, contains(), provides the ability to search for an object within the list. A common question arises regarding how this method determines if two objects are equal.
The Role of equals() Method
ArrayList incorporates the List interface, which defines the contains() method. As per the List interface specification, the contains() method calls the equals() method to compare objects for equality.
Default equals() Behavior
By default, the equals() method compares objects for referential equality, which means objects are considered equal only if they refer to the same object instance. This behavior is not suitable for most custom classes, where equality should be based on the object's attributes.
Overriding equals() for Custom Classes
To achieve semantic equality for your custom classes, you need to override the equals() method. In your example, you have provided an implementation of equals() that compares based on the value attribute of the Thing class.
Example Evaluation
Using your provided implementation of equals(), let's evaluate the contains() method:
ArrayList<Thing> basket = new ArrayList<>(); Thing thing = new Thing(100); basket.add(thing); Thing another = new Thing(100); basket.contains(another); // true
The contains() method returns true because the overridden equals() method compares the value attributes of both thing and another and determines them to be equal.
Hence, to enable the contains() method to correctly identify objects based on their attributes, it is essential to override the equals() method and provide a meaningful implementation for comparison.
The above is the detailed content of How Does ArrayList's `contains()` Method Evaluate Object Equality?. For more information, please follow other related articles on the PHP Chinese website!