.Contains() method not calling Overridden equals method

This is because your equals() is not symmetric:

new Foo("ID1").equals("ID1");

but

"ID1".equals(new Foo("ID1"));

is not true. This violates the equals() contract:

The equals method implements an equivalence relation on non-null object references:

  • […]

  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

It is not reflexive either:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
Foo foo = new Foo("ID1");
foo.equals(foo)  //false!

@mbockus provides correct implementation of equals():

public boolean equals(Object o){
  if(o instanceof Foo){
    Foo toCompare = (Foo) o;
    return this.id.equals(toCompare.id);
  }
  return false;
}

but now you must pass instance of Foo to contains():

System.out.println(fooList.contains(new Foo("ID1")));
System.out.println(fooList.contains(new Foo("ID2")));
System.out.println(fooList.contains(new Foo("ID5")));

Finally you should implement hashCode() to provide consistent results (if two objects are equal, they must have equal hashCode()):

@Override
public int hashCode() {
    return id.hashCode();
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)