Search code examples
javacompareto

How does the comapareTo method in Java works?


Can anyone explain how does the following codes works?

public int compareTo(Object o) {
    if (o instanceof Item) {
        return date1.compareTo( ((Item) o).getDate2());
    }
    return -1;
}

Solution

  • It check that object o is an item, then compares them, the compare to function returns the values, -1, 0 and 1.

    If it returns a value of 0 it means the objects are the same, if it return -1 or 1 it is saying that they are not the same.

    The return at the end is the default catch, so if object o is not of that item type return no match.