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 trialThomas Williams
9,447 PointsWhen is the compareTo parameter entered?
I feel I largely understand this except I am a little confused about when precisely this compareTo method is run. compareTo(Object obj) with Treet other = (Treet) obj I think requires the input of an actual created Treet as a parameter but when does this happen? When does each Treet get compared to each of the other Treets. Is it when Arrays.sort is used? (Sorry if this is a poorly worded question!).
2 Answers
Craig Dennis
Treehouse TeacherYou are right! Anyone can call the method as it is public, but the Arrays.sort
method uses that compareTo
method to figure out the proper ordering of all elements in the array.
Thomas Williams
9,447 PointsThank you!
Philip Bradbury
33,368 PointsPhilip Bradbury
33,368 PointsHi, How does arrays.sort know to call the method and add another treet in the compareTo parameter?
Craig Dennis
Treehouse TeacherCraig Dennis
Treehouse TeacherIt is just sorting it's own elements. It compares the first two elements and places them in the right order then compares the next two, and puts those two in the right order, and so on and so forth. It is using an algorithm to do that, but the way it compares is using the
compareTo
method provided by implementers of theComparable
interface.I was going to use an analogy of students in a line and then I found this gem of students acting out algorithms, note that when trying to figure out how one should be sorted compared to the next person, they are essentially calling the
compareTo
method.Philip Bradbury
33,368 PointsPhilip Bradbury
33,368 PointsThank you for the reply, i understand how the compareTo method works just now how the Object Obj parameter comes into play. How does "compareTo(Object obj)" in the treet class know to compare the current treet with the next one.