Hi
Suppose I have a Player class. From that class, I create 2 objects
Player p1 = new Player("Jen");
Player p2 = new Player("Jen");
then why is p1.equals(p2) is evaluated to false?
Printable View
Hi
Suppose I have a Player class. From that class, I create 2 objects
Player p1 = new Player("Jen");
Player p2 = new Player("Jen");
then why is p1.equals(p2) is evaluated to false?
The equals() method is inherited from Object. In object, the equals method is defined to return true if and only if the two objects are the same object. By same object, I mean exists in exactly the same space in memory (so x == y would return true).
In the case of your example, the objects are not the same. They contain the same information, but they are seperate objects. It's the same as if we have two identicle cars side by side, same make/colour etc. They are still seperate cars.
If you want to alter the equals method so that it discriminates based on the properties of the object rather than its memory address you have to override the equals method. You could then test that all the properties of one object (such as name, age etc in a person) are the same as in the other object.
For more information on the equals method see the API for Object which can be found here.
Hi
Do you mean that in my example, the .equals method is comparing the memory addresses of the two objects? Since they are not the same so Java returns false.
Thanks for your response.
Yes, thats exactly what I mean. That is what the default .equals() method in Object does. If you want it to do anything else you have to override it. For example, the String class compares the characters in two strings to see if they're the same. That way to seperate string objects can be declared equal.
You can simply override the method in your Player class. That way, you can set it up so that two Player objects are equal if they have the same name or something.
yes, because java isnt artificially intelligent enough to know that two objects that just happen to hold the same string, are equal.. so all it goes off is the memory location..Quote:
Originally posted by scracker
Hi
Do you mean that in my example, the .equals method is comparing the memory addresses of the two objects? Since they are not the same so Java returns false.
Thanks for your response.
whether or not they are infact equal, is a choice you have to make. you make it by rewriting .equals to compare the things youre interested in.. i.e. player names