I was doing a small test in Java, when I was having trouble with my program working. I tried to see if I could replicate the problem; now that I have, I don't really understand why it is a problem. Any help would be awesome.
Could anyone explain why this yields untrue?
Book myBook = new Book("Something", 352);
Book yourBook = new Book("Something else", 125);
Book ourBook = new Book("Something", 352);
Book theBook = ourBook;
System.out.print(theBook.equals(myBook));//False, but logically true
My problem is that theBook is a pointer to ourBook and ourBook has the same values as myBook, thus it seems logical through the transitive property that theBook is equal to myBook, hence outputting true. Nonetheless, this is not the case. It should be noted that Book is simply an arbitrary class that I made for an example. Could it be because of hash codes?
Result of equals call is False because you are comparing two different instances of the class Book.
A.equals(B) returns True IFF (if and only if) both A and B refer to the same instance. It is called a shallow comparison because it compares only references to the instances and NOT the fields inside instances. Transitive property of equal method only applies if three or more variables refer to the same instance.
You should look up the documentation for java.lang.Object class to see functional description of equals method.
You should also note that equals method inside java.lang.String class behaves differently (it does by-character comparison of two string values, hence a deep comparison) than the one in Object class. This is might be the reason of your confusion.
Ah, I see. Thank you. I thought it was something to do with references/hashs since theoretically I could have a class with a massive amount of variables, which would make .equals very slow. So the same experiement but with Strings would equate to true?
You can also achieve the desired affect by overriding the equals() method within your class.
public boolean equals (Object book2){
if (this.name == book2.name && this.theintinyourconstructor == book2.theintinyourconstructor){
return true;
} else {
return false;
}
I believe using Book in place of Object will not work correctly as the equals method that is being inherited takes an Object. I have not used Java in a while so take that with a grain of salt haha. Good luck!