0

My main problem is that the contains() method on my ArrayList returns always false, and I am not sure why.

I have created an ArrayList<Position> called allValidPositions, which contains many instances of my custom class called Position.

When I try to find a specific Position element in the ArrayList, it always returns false.

// The parameters represent X and Y coordinates
Position positionToCheck = new Position(0, 0);

if (allValidPositions.contains(positionToCheck) {
    System.out.println("Found");
} else {
    System.out.println("Not found");
}

It always prints Not found although I know that there is a Position that should be the same object (the fields and values in the objects are the same).

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
Zopy
  • 149
  • 1
  • 2
  • 9

1 Answers1

7

contains() method is dependent on equals() method of the object contained within the list. In this case, make sure you have properly overridden equals() method in the Position class.

How contains() works?

It picks up each object in your list and tries to equate it with the object that you passed by calling equals() method. Only if equals() is properly overridden you will be able to check logical equality. Otherwise, it will only return true if you pass the same reference.

Edit:

As per comment by @AselS, contains() is dependent on indexOf() which calls equals().

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
  • Minor clarification: `contains()` utilizes the `indexOf()` (which has a helper method) that relies on `equals()`. – asathkum Aug 24 '19 at 06:34
  • @AselS Thanks for that. Added the clarification. – Narendra Pathai Aug 24 '19 at 06:36
  • Thanks for your help, I really appreciate it! With the correct override, it works perfectly now. Thank you again! :) – Zopy Aug 24 '19 at 06:52
  • @NarendraPathai Ohh, and really thank you for your code edition. It really made my question more readable, and I have learned a lot from it. With your help, I'll post better questions in the future! Thanks for that as well! – Zopy Aug 24 '19 at 06:58
  • @Zopy You are welcome, my friend. Make sure next time you also check if a similar question has been asked previously. Great that you are willing to learn and be a better SO citizen. All the best for your journey. – Narendra Pathai Aug 24 '19 at 08:41