Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Mechanism of method equals(Object obj) for class Treet

Hello, everyone. I still dont get point how function equals(other) for Treet class works. How is supposed to be equals for two instances of Treet class if we dont override this method? Yes, we use type casting, but how we compare two instances of Treet and find them equal? In a declaration in method equals (Object obj)there is alternative use of operator '=='.

public boolean equals(Object obj) { 
Β Β return (this == obj); 
}

But operator '==' compares references of Objects and doesnt identify its content. If im wrong, please correct me. Thx for your responses.

2 Answers

equals use "==" inside to compare what ever you decide to be the comparable but if you didn't override the equal and the hash then it compares the reference of the objecct. equals use the hash-code to compare while The == operator tests whether two variables have the same references . check these would be helpful https://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java https://www.ibm.com/developerworks/java/library/j-jtp05273/index.html http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

Thank you very much. I think, i get it. So, if we dont override methods equals(Object obj) and hashCode(), equality instances of class would be check by default method equals(Object obj) from class Object and similar to '==' .

If we don't override methods equals(Object obj) and hashCode() then equals would use "==" to compare the auto generated hashcode but if we use "==" it will check for the location or the address in the memory not the actual value the examples in this topic is really helpful http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/