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 Java Data Structures - Retired Organizing Data Interfaces

Mahmoud Amin
PLUS
Mahmoud Amin
Courses Plus Student 6,269 Points

Why check equality

In this code

public int compareTo(Object obj){

/* I understand that here we cast the object obj to the class Treet then we assign the other variable to equal obj */

Treet other = (Treet) obj;

/* Why do we check equality between obj and other if we already assigned them to be equal at the previous step.*/

if(equals(other)) { return 0; } }

2 Answers

Kourosh Raeen
Kourosh Raeen
23,733 Points

You're not checking equality between other and obj. You're checking equality between the object that invoked the equals method and other. The line:

if(equals(other))

is really this line:

if(this.equals(other))

where this refers to the current object, the one that equals() was called upon.

Mahmoud Amin
PLUS
Mahmoud Amin
Courses Plus Student 6,269 Points

Thank you so mch I really didn't know about (this) keyword

Kourosh Raeen
Kourosh Raeen
23,733 Points

Glad I could help! Happy coding!