I have a List<Person> objects where person is defined like so
public Person {
private firstName;
private lastName;
//getter and setter methods
public boolean equals(Object obj) {
return lastName.equals(obj.toString());
}
}
Now I want to see if this List<Person> contains a certain last name.
if(myList.contains("Smith"))
System.out.println("yay!");
However the way the contains method is specified is that is returns true when (o==null ? e==null : o.equals(e)). So in this instance it is using String.equals(Person) instead of Person.equals(String). Is there a simple way of fixing this or do I have to write my own logic for contains?
No, not using
Collection.contains.By the contract of
equalsthe implementation must be symmetric:This means that returning any thing else than
falseforsomePerson.equals(someString)is a direct violation of the contract.Yes. Use a for loop:
or, if you’re using Java 8,