Skip to main content
gamedev.net
🔒 Locked

java doubt...

Started by FreJa 1 reply 450+ views
Original Post
FreJa
FreJa
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
"Through me the road to the city of desolation,Through me the road to sorrows diuturnal,Through me the road among the lost creation."
Vyper_uk
Vyper_uk
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
rohde
rohde
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].
"We confess our little faults to persuade people that we have no large ones." -Francois de La Rochefoucauld (1613 - 1680). | My blog

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.