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

Mike B
Mike B
10,424 Points

confused about compareTo

In the lesson, we are overriding compareTo but immediately after creating a Treet and casting obj, we are typing:

"if (equals(other)) {"

shouldn't we be defining something to equal other? Like "if(treet.equals(other))"?
I'm confused as to how the method knows what we are comparing.

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Mike,

inside the Example class you call sort() and the method takes a Treet object "treets". When sort() is called the compiler goes to the compareTo() method inside the Treet class.

When compareTo() is been called the Treets are already created in Example.

The compareTo() method takes an object "obj". This Object is "treets" from sort(treets). After casting "treets" as Treet and naming it "other" you call equals() on Treet class and "other will be compared to Treet.

I hope it makes the concept more clear

Grigorij

2 Answers

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hey Mike,

I had the same question some days ago ... look here:

[ https://teamtreehouse.com/community/compareto-question ]

If you still confused, we can go over the topic and exchange our confudes thoughts :)

Grigorij

Mike B
Mike B
10,424 Points

I noticed your post but I thought it directly related to the task and I didn't want the answer. I think I understand my original question, but now I'm confused as to how we are comparing a Treet to another from within the Treet class.

I feel like the Example class should be calling the compareTo method...it is where the Treets are being created. How is Treet comparing itself to another when neither exist yet?

Not sure if I'm explaining myself properly but the sorting is done through example so I feel like the compareTo should be done in Example as well

Mike B
Mike B
10,424 Points

Thanks, Grigorij

It definitely makes more sense the way you explained about the sort method which IS in the Example class...that helps a lot!

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Great to hear it, Mike !!!

I am glad that I could help a little bit

Grigorij