开发者

Java: howto write equals() shorter

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 eas开发者_如何学JAVAily 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.


There are libraries that'll do it for you. For example, commons-lang has EqualsBuilder

Also, these two lines appear to do the same thing:

            if (o == null)
                    return false;
            if (null == (Id) o)
                    return false;

Maybe you meant this:

            if (o == null)
                    return false;
            if (this == o)
                    return true;


Project Lombok also has a equals and hashCode generator using the @EqualsAndHashCode annotation which has the advantage of being in sync with the current class/source code. I'm not sure about the implementation details but definitely worth looking into if you need to cut down the cruft.


A simpler way (other than generating the code) might be.

public boolean equals(Object o) {
   return o instanceof Id 
        && (name == null ? ((Id)o).name == null : name.equals(((Id)o).name);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜