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

Java Core

Created by mpecher. Last edited by mpecher, 5 years and 185 days ago. Viewed 533 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
no comments | post comment

Menu:
Java & J2EE
Development
Books

Help:
Help FAQ
Formatting


< February 2012 >
SunMonTueWedThuFriSat
1234
567891011
12131415161718
19202122232425
26272829


Logged in Users: (1)
… and 10 Guests.



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.