[ start | index | login ]
start > Development > Java & J2EE > Java Core

Java Core

Created by mpecher. Last edited by mpecher, 5 years and 296 days ago. Viewed 537 times. #3
[diff] [history] [edit] [rdf]
labels
attachments

Override equals() and hashcode()

When ever equals() is overriden, so should hashcode() (see Effective Java ). Use the commons lang EqualsBuilder, HashCodeBuilder, ToStringBuilder for constructing these.

equals()

The equals method allow direct access to the instance variable of the object being compared to. Direct access to the properties should be avoided where possible, instead the getter methods used. This is important, since the object instance obj passed to equals might be a proxy object, not the actual implementation that holds the persistent state (ie. when used through Hibernate etc).

/**
     * override default equals implementation.
     * 
     * @param obj
     *            to compare
     * @return whether the two object are equal.
     */
    public boolean equals(Object obj) {
        //short cut for same reference
        if (this == obj) {
            return true;
        }

if (!(obj instanceof Column)) { return false; }

Column o = (Column) obj; return new EqualsBuilder() .append(refCol, o.getRefCol()) .append(isVisible, o.isVisible()) .append(sortDir, o.getSortDir()) .append(name, o.name) // (1) direct access should be avoided .isEquals(); }

Here at (1) o.name is permissable, but its convience method should be used ie. o.getName().

Eclipse plugin

Plugin allows generation of hashCode(), equals(), toString() and compareTo() using commons lang Builders.
>>http://commonclipse.sourceforge.net/index.html
Please login to post a comment.

Menu:
Java & J2EE
Development
Books

Help:
Help FAQ
Formatting


< May 2012 >
SunMonTueWedThuFriSat
12345
6789101112
13141516171819
20212223242526
2728293031


Logged in Users: (0)
… and a Guest.



Disclaimer: Views and opinions are that of the individual author, and not that of Marand Custom Solutions. This site is an open forum for technical content, and the company accepts no liability for any content or view expressed.