Original Post
🔒 Locked
java doubt...
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
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
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].
Read more here:
equals [Java Glossary].
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement