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

Xuanzheng Lin
Xuanzheng Lin
2,466 Points

The use of equals method in overriding the compareTo

Craig had the code like this

@Override
public int compareTo(Object obj) {
    Treet other = (Treet) obj;
    if (equals(other)) {
        return 0;
    }
    ......
}

I wonder why not the equals method like the name of the object to be compared.equals(other)?

1 Answer

public class Treet implements Comparable {

.... @Override public int compareTo(Object obj) { //method takes in a class and returns an int

Treet other = (Treet) obj;                  //just placing the target into a variable class inst

if (equals(other)) {                        //if x.compareTo(y) == 0, return 0;

    return 0;                       //stop this method, they are the same

}
int dateCmp = mCreationDate.compareTo(other.mCreationDate); //otherwise keep going and compare the class' variables

    int descriptionCmp = description.compareTo(other.description);

    int authorCmp = author.compareTo(other.author);


    if (dateCmp == 0) {                     //if similarities occur, return them

        if (descriptionCmp == 0) {

            return authorCmp;

        }
        return descriptionCmp;

    }
    return dateCmp;

}

}