I am having an issue where I make an ArrayList of Foo objects, I override the equals method, and I cannot get the contains method to call the equals method. I have tried ove
You should implement hashCode
@Override
public int hashCode() {
return id.hashCode();
}
even though the contains works for ArrayList without it. Your big problems are that your equals expects String, not Foo objects and that you ask for contains with Strings. If the implementation asked each eject in the list if they were equal to the string you send, then your code could work, but the implementation asks the string if it is equal to your Foo objets which it of course isn't.
Use equals
@Override
public boolean equals(Object o){
if(o instanceof Foo){
String toCompare = ((Foo) o).id;
return id.equals(toCompare);
}
return false;
}
and then check contains
System.out.println(fooList.contains(new Foo("ID1")));