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
Rey Adronico Baguio
13,672 PointsComparable Treet question
I didn't understand how Craig was able to order an array of Treets. Here's what I understood:
He overrode the compareTo() method from Comparables.
He then instantiated a new Treet and typecasted the required Object "obj" as a Treet.
He then wrote this code and this is where I get lost:
if (equals(others)) { return 0; }
I don't quite understand what that actually means considering equals is a method (but it's not attached to an object in this case). If it's compared to obj, why do we have to compare it to "others" considering we just instantiated others using obj.
Lastly, Can we call the compareTo() method (in class Comparable) inside a method declaration of compareTo (in class Treet) as Craig did?
Rey Adronico Baguio
13,672 Pointspublic 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; }
1 Answer
piyush arora
5,735 PointsHi Rey,
if(equals(other))...This simply means this.equals(other) i.e the current Treet object is compared to object reference passed i.e obj typecasted to other (Treet). If both objects are equal i.e we are talking about the same object, 0 is returned.
int dateCmp = mCreationDate.compareTo(other.mCreationDate)
This is where comparison happens based on the creation date of the treet...mCreationDate(Date Object implements Comparable Interface) to other.mCreationDate(other->Treet instance has property mCreationDate) ...If both treets were created on the same date i.e datecmp==0 then comparison is made on the description i.e
mDescription.compareTo(other.mDescription)
If this also same then the we are about the same treet...0 is returned!!
Hope this helps!!
Enrique MunguÃa
14,311 PointsEnrique MunguÃa
14,311 PointsCan you provide the code snippet please?