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 Organizing Data Interfaces

Lakshmi Narayana Dasari
Lakshmi Narayana Dasari
1,185 Points

Arrays.sort(treets)

Treet[] treets = {treet , secondTreet}; Arrays.sort(treets); // here the compareTo method will be called as the class implements comparable interface.

when we write

public int compareTo(Object obj); // what is that we are passing to Object obj ? is it the treets from Arrays,sort(treets)? if thats the case we are passing an array of objects,then what should we consider Object obj = treet or Object obj = secondTreet?

if(equals(other)) // i know that current object is compared to the passed object..but what exactly is current object and passed object here? current object is treet and passed object is secondTreet?

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

compareTo() gets passed a single element of the array, in this case a single Treet. Since compareTo() is called from a Treet (like this: treetOne.compareTo(treetTwo) , obj is the second Treet.

Inside compareTo(), like all object methods, there is a special variable called "this" which refers to the object the method was called on. In my example above, this would equal treetOne. You can call a method from this just like any other object, this.method(). if(equals(other)) is the same as if(this.equals(other)). We're just allowed to drop the "this." if it's unambiguous and leave it implicit which is most of the time. Which is why you don't see "this." all that often in Java code.