This is a question about how to implement the equals method when I need to find instance of the object in a List given a value that one of the instances my have in their member.
I have an object where I’ve implemented equals:
class User {
private String id;
public User(id) {
this.id = id;
}
public boolean equals(Object obj) {
if (!(obj instanceof User)) {
return false;
}
return ((User)obj).id.equals(this.id);
}
}
Now if I want to find something in the List I would do something like this:
public function userExists(String id) {
List<Users> users = getAllUsers();
return users.contains(new User(id));
}
But perhaps this might be a better implementation?
class User {
private String id;
public boolean equals(Object obj) {
if (!(obj instanceof User)) {
return false;
}
if (obj instanceof String) {
return ((String)obj).equals(this.id);
}
return ((User)obj).id.equals(this.id);
}
}
With this instead:
public function userExists(String id) {
List<Users> users = getAllUsers();
return users.contains(id);
}
Do not override equals for things that are not mathematically equal.
You might think it is a good idea to do
but it rarely is. Do you want all of the equals observing code getting confused when
Stringsare “equal” toUsers?If you want a lookup method, write it
Then the code elsewhere to maintain the “fast lookup” table.
Note that this doesn’t mess around with the equals implementation, so now you can safely have
SetsofUsers,ListsofUsers, etc. all without worrying if somehow a String will foul the works.Now if you can’t find a good place to maintain a
MapofUsersindexed by theirid, you can always use the slowerIteratorsolution