I get headaches when I have to write nearly 10 lines of code to say 2 Objects are equal, when their type is equal and both's attribute is equal. You can easily see that in this way of writing the number of lines increase drastically with your number of attributes.
public class Id implements Node {
private String name;
public Id(String name) {
this.name = name;
}
public boolean equals(Object o) {
if (o == null)
return false;
if (null == (Id) o)
return false;
Id i = (Id) o;
if ((this.name != null && i.name == null) || (this.name == null && i.name != null))
return false;
return (this.name == null && i.name == null) || this.name.equals(i.name);
}
}
Google's guava library has the Objects class with Objects#equal that handles nullness. It really helps get things smaller. With your example, I would write:
@Override public boolean equals(Object other) {
if (!(other instanceof Id)) {
return false;
}
Id o = (Id) other;
return Objects.equal(this.name, o.name);
}
The documentation is here.
Also note that there is Objects#hashCode and Objects#toStringHelper to help with hashCode and toString as well!
Please also see Effective Java 2nd Edition on how to write equals().
If you use Eclipse, click "Source" -> "generate hashCode() and equals()". There're many options to create equals() automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With