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 trialAbhishek Upadhyay
2,986 PointsI am still not sure how does this compareTo function is getting called internally
I am still not sure how does this compareTo function is getting called internally and how does the return statements are contributing to the comparison we want to achieve here.
Can some one please simply explain why/how we achieved comparison from Comparable interface + compareTo function here in simple terms.
Apologies in advance.
1 Answer
Balazs Peak
46,160 Points"how does this compareTo function is getting called internally"
-> What I'm getting here is that you want to know, how come that we implement the compareTo function in a class, but yet we are calling the same compareTo function internally, to get the result? - well, we are doing this because in the class we have created, there are many fields on which the comparison could be calculated on. For example, if there would be a "TreehouseStudent" class, and you and me were objects, we could be compared by our name (alphabetically), our age, our Treehouse Points. So we have to specify what data would do the comparison, when comparing objects of our own custom made class. And the reason we can use the same method inside is that in classes, which are part of the Java language core (String, Date, int.... etc), compareTo already has been implemented.
"how does the return statements are contributing to the comparison we want to achieve here"
-> Basically, if you have an array with objects of a particular class, you can call a "sort()" method on that array. Now this "sort()" method has such a code that it can only sort if the Comparable is implemented in that class which it is about to sort. This "sort()" method will know very well how to use this compareTo method, it will compare two objects, if the result is -1, the first goes one step back in the queue... etc.
I hope this makes sense! Much love! Keep up the good work!
Abhishek Upadhyay
2,986 PointsAbhishek Upadhyay
2,986 PointsThanks . This makes sense to me.
Balazs Peak
46,160 PointsBalazs Peak
46,160 PointsYou are most welcome! Happy to help! If you's like you can have me on facebook and ask me anything that comes up! Click my name and check my profile, there will be my contact info