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

Serghei Berezovschi
Serghei Berezovschi
13,360 Points

How does Object obj get passed into compareTo method?

I doesn't look like this method gets called in any of the classes.

1 Answer

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

Could you be more specific what exactly you don't understand?

How does Object obj get passed into compareTo method?

Object obj is passed as argument:

compareTo(Object obj) ... ?

About this:

I doesn't look like this method gets called in any of the classes.

It gets called behind the scenes, when you write sort on the Array containing Treets. If the array contains objects that implement Comparable and @Override compareTo, sort function uses that to sort Array...

Read docs description of sort method:

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(java.lang.Object[])

Quote from it:

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

Does it make sense ?

tomtrnka
tomtrnka
9,780 Points

Finally, great answer. I was wandering what is the connection between Arrays.sort() and compareTo() . Why do we implement Comparable interface. It wasnt that clear from the video :)