Sign in to follow this  

[java] Object.equals()

This topic is 4557 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a neater way to implement this method for a homemade class than:
public boolean equals(Object other)
{
     if(other.getClass()==this.getClass())
     {
          // do stuff to check for equality
     }
     else
     {
          return false;
     }
}

It does the job but it seems so hacky. Java is not my language of choice.

Share this post


Link to post
Share on other sites

// Initialized somewhere
Sprite a;
if (a instanceof Monster) {
// Do something with the monster
} else if (a instanceof Player) {
// Do something with the player
}



And the equals() method usually checks the hash pattern to identify the equality between two objects, if I remember well.

Son Of Cain

Share this post


Link to post
Share on other sites
According to the J2SE reference on Sun's website, overriding one sort of implies that you should override the other. The implication is that if a.hashCode()=b.hashCode() then a.equals(b), but not the other way around, I think. Or maybe it's reversed.

Anyway, it suggests overriding both if you override one, and that's what I've done. Thanks for the tips.

Share this post


Link to post
Share on other sites

This topic is 4557 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this