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

Why does we put Object obj as parameter inside compareTo method?

When watching the <a href="https://teamtreehouse.com/library/java-data-structures/organizing-data/interfaces">Interfaces video</a>, we are overriding the compareTo method and put the Object obj as the parameter, how does this help the class to sort things out?

1 Answer

As you can see from the Java 8 documentation here: https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

Comparable helps you compare two objects. Returning a negative value, zero, or positive value if the value is less than, equal to, or greater than the specified object.

Java knows how to compare things like Strings and Integers because they are built in classes within Java. But let's say you are writing a User class, a Post class (For a social network, for example), or a Photo class to store information about a photo, Java does not know how to determine whether two objects of one of these classes are equal to one another.

You, as the creator, may want to decide that a user is equal only if the usernames are identical, or maybe you allow similar usernames but unique registration emails. for your post class you may compare the text, but you may also want to compare the date and user who created a post, and on and on for different classes.

The Comparable interface, along with the CompareTo() method, allows you to specify under what scenarios two objects from a custom class are equal, and when one should go before another when sorting them.

Hope this helps :)

Thank you so much for the explanation, make the topic much clear now. However, the example code inside the video confuse me a little bit, for now i cant figure out how the object treet is being compared. I understand about the return value, it just i didnt understand what item is being compare to obj.

Sorry if my question is a bit hard to understand, this maybe due to English is not my native language.