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 trialAndrew D.
2,937 PointsHow Is the Second(or third.. fourth) Object Called for Comparison?
Hey guys.. I understand everything(well, most of it) INSIDE of the toCompare method:
public int compareTo(Object obj) { Treet other = (Treet) obj; if(equals(other)) { return 0; } int dateCmp = mCreationDate.compareTo(other.mCreationDate); if(dateCmp == 0) { return mDescription.compareTo(other.mDescription); } return dateCmp; }
But what I don't understand is how a single obj parameter is comparing itself against all of the other treet objects that are in our Treet[] treets array. The compareTo function doesn't seem to call itself, and the lone parameter is quickly cast into the 'other' variable.
So to a person new to programming, it seems the entire method is comparing the Treet object 'other' to.. well, itself. And not another treet.
Can anyone provide clarification, please?
Thanks,
Andrew
1 Answer
Allan Clark
10,810 PointsThis is a method on the Treet class. So whenever this method is called it will be called on a Treet object and sent a second Treet to compare. Lets say we have 2 Treets, treet1 and treet2. We would use the compareTo() like this:
treet1.compareTo(treet2);
treet2 will be the obj parameter in the compareTo() method (the one that gets cast into a Treet). We do not have to explicitly code that we are comparing it to treet1 because that is what the method is being called on. You could change the if conditional to be more explicit by using the 'this' keyword.
if(this.equals(other))
Hope this helps, let me know if any more clarification is needed.