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

Jake Goodman
Jake Goodman
3,381 Points

equals(Object obj)

At the beginning of the method compareTo(). we check if (equals(other)). I am not clear as to what is being compared at this line. We have seen the .equals() method on Strings, where there is a string being compared to another string: For example : "banana".equals("apple") But in the example above: if (equals(other)) I have no idea what is being compared. What is being compared to other?

4 Answers

You are comparing the current instance of Tree to 'other'. other will be another instance of Tree that is passed into the compareTo() method. So you will essentially call it like this:

Tree tree1 = new Tree() //i don't know what goes into the constructor so i just leave it blank for demonstration only
Tree tree2 = new Tree()

tree1.compareTo(tree2); //tree2 is other in this case. 

I'm having the same question he had. I kinda get what you said, but a bit of doubt still remais. I didn't know you could com a method (like equals()) without calling it on an object. I've seen until now all methods being called on objects using a dot.... I'm supposing that there are cases you can just call it like Craig did.

This might be a shorthand for "this.equals(other)". Is that right, or am I missunderstanding something here?

or yochanan
or yochanan
1,312 Points

When you don't provide a prefix to equals, it assumes you mean "this.equals(..)". The "this." annotation means: the instance you're invoking the handler from.

if (equals(other)) compares the object references. It checks if its in the same place in memory.