Java Java Data Structures 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;

}

}