Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Can someone help me overide hashcode and .equals for this entity class?

800296Jul 12 2009 — edited Jul 15 2009
I find this a little tricky and could use some help. Here is what I have so far...
@Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Contact)) {
            return false;
        }
        Contact other = (Contact) object;

        // Every contact must have a name and surname.
        // If these match then we validate the numbers.
        if ((this.name.equals(other.name)
                && this.surname.equals(other.surname))) {
            // Check the numbers using a shallow validation
            if ((this.homeNum != null
                    && !(this.homeNum.equals(other.homeNum)))
                    || (this.workNum != null
                    && !(this.workNum.equals(other.workNum)))
                    || (this.cellNum != null
                    && !(this.cellNum.equals(other.cellNum)))
                    || (this.email != null
                    && !(this.email.equals(other.email)))) {
                return false;
            }
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += this.name.hashCode();
        hash += this.surname.hashCode();
        if (this.email != null) {
            hash += this.email.hashCode();
        }
        if (this.workNum != null) {
            hash += this.workNum;
        }
        if (this.cellNum != null) {
            hash += this.cellNum;
        }
        if (this.homeNum != null) {
            hash += this.homeNum;
        }
        return hash;
    }
I want to imply the logic that to contacts are equal if their name and surname match and then if any of their email or phonenumbers match. The logic here is that people may share the same number. As you can see by my documentation I am ensuring that each contact must have a name and surname.

Edited by: Yucca on Jul 12, 2009 7:00 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 12 2009
Added on Jul 12 2009
35 comments
714 views