Jump to content
  • Advertisement
Sign in to follow this  
FreJa

java doubt...

This topic is 4634 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

Hi, I created a bunch of classes, and in each class I want to have an equality method, that works like: Car c1, c2; Bike b1; ... c1.equals(c2); b1.equals(c1); how can I implement this equals class? Thanks

Share this post


Link to post
Share on other sites
Advertisement
I believe that the standard way that Java does equality is to test the hashcode of the objects. However, this will only test wether or not the two objects are actually the same in memory, eg c1.equals(c1) would return true but c1.equals(c2) would return false.

What you want to do is override the

public boolean equals(Object obj)

method in the object class. Then you need to test all the relevant things within the classes to see if they are equal. First you should test that both objects are the same class by using instanceof and then check that each variable is the same within each object

Then you should probably also override the

public int hashCode()

method, so as to ensure that equal objects always have the same hashcode and things like hashtables will work with your objects. If you still want hashtables to work properly without doing this just leave the default equals method the same and use your own, eg

public boolean isEqualTo(Object obj)

However if you do this then any other class not written by you which tests for equality will use the default test again (the hashcode). It all depends on how you want the rest of the language to interact with your classes

Share this post


Link to post
Share on other sites
The equals method is defined in the Obejct class, so it's already there. You just need to override it so it makes sense for your class - when overriding the equals method you should also override the hashCode method.

Read more here:
equals [Java Glossary].

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!