Explain Codes LogoExplain Codes Logo

How does an ArrayList's contains() method evaluate objects?

java
equals-method
hashcode-method
collections
Nikita BarsukovbyNikita Barsukov·Dec 8, 2024
TLDR

The ArrayList's contains() method verifies if a given object is present in the list using its equals() method. It loops through the list, comparing the passed object with each element. The logic is essentially o.equals(elementData[i]). If the comparison returns true even once, bingo! — the object is in the list.

// For non-null objects for (int i = 0; i < size; i++) { if (o.equals(elementData[i])) { return true; // Eureka! Object found! } }

Customize the equals() function according to requirements. By default, it compares memory addresses (loves playing hide & seek with reference equality), which might not be your cup of tea when dealing with logical value comparisons.

Getting grip of the bits and bolts

Here we need equals(). This method holds the reputation of being a contract rather than a suggestion when ditching contains(). By adhering to a well-designed equals(), the ArrayList can reliably compare objects beyond vanilla reference equality.

Tuning equals and hashCode

Remember to override both equals() and hashCode() when comparing objects based on what they are (their contents), not by their suit (reference). It's like having password and fingerprint scan at the secure entrance, with one being helpless without the other. Neglecting this can lead to mind-boggling behavior oddities and performance hiccups.

Mind the gaps using contains()

Even if two objects are born from the same constructor arguments, they won't be treated as twins unless equals() and hashCode() have been appropriately tweaked. This is specially important when you have collections like HashSet in the mix with ArrayList.

Common pitfalls

To navigate the rough terrains:

  • Null handling: In your custom equals(), null is not your enemy. Handle it gracefully, else you’ll be pulling hair over NullPointerExceptions.
  • Type checking: Your equals() should also pass the type checking test to prevent a jarring ClassCastException.
  • Symmetric equality: For any two objects x and y, it’s highly expected that if x thinks y is a friend, then y should also think x is a friend i.e., x.equals(y) should imply y.equals(x).

Considerations for optimal performance

When balancing performance:

  • The equals() method’s efficiency can shape the contains() method's overall execution speed.
  • A dodgy hashCode() method could inflict a collision traffic jam leading to painfully slow look-ups in hash-based collections.