Java: howto write equals() shorter

Posted by erikb on Stack Overflow See other posts from Stack Overflow or by erikb
Published on 2011-01-05T04:16:36Z Indexed on 2011/01/05 5:53 UTC
Read the original article Hit count: 82

Filed under:

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

}

© Stack Overflow or respective owner

Related posts about java