Java Java Data Structures 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. 
Ewerton Luna
Ewerton Luna
Full Stack JavaScript Techdegree Student 15,132 Points

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.