Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: howto write equals() shorter

Tags:

java

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);
        }

}
like image 706
erikbstack Avatar asked Jan 05 '11 04:01

erikbstack


2 Answers

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().

like image 160
Tom Avatar answered Sep 22 '22 12:09

Tom


If you use Eclipse, click "Source" -> "generate hashCode() and equals()". There're many options to create equals() automatically.

like image 27
卢声远 Shengyuan Lu Avatar answered Sep 22 '22 12:09

卢声远 Shengyuan Lu