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

public int compareTo(Object obj){ Treet other = (Treet) obj; if(equals(other))

I didn't understand this part. can someone give a better idea to understand. pls

3 Answers

public int compareTo(Object obj){ Treet other = (Treet) obj; if(equals(other)) The code is overriding the compareTo method of the Object class, from which all other Java classes inherit from. The method takes a single Object instance as an argument. The first thing it does is casts the Object instance as a Treet called "other". Then it is checking if other "equals" the Treet instance for which the method is being invoked. The equals method is doing a comparison by reference; it will return true if the "other" object is in fact the same object as the Treet instance for which the method is being invoked. If this is true, the method returns zero. If not, it performs other comparisons in order to return the correct answer, which could still be positive, negative, or zero, based on the contents of the two distinct objects.

so, "if(equals(other))" is making short that there are not any other ?? I removed it form my program and still working perfect. on my opinion that line is is trying to make short that there are no any 'other' around.

correct me if I'm wrong pls. thx Iver

Fernando,

You could say that. "if(equals(other))" returns true if the objects have the same reference, so they are the same, i.e. as you put, there is not any other. I am not surprised that your program works the same without it, since if a single object's values are compared to themselves, the result will be the same as two separate objects that are the same as each other. "if(equals(other))" is just a way to save compute resources by trying the simplest possible comparison first.

Iver