[Java] [Read Effective Java] Chapter 3, Item 12 Examine the implementation of Comparable

less than 1 minute read

Consider implementing #Comparable

Unlike the other methods, the compareTo method is not declared in Object. To be precise, the compareTo method is the only method of the Comparable interface. If you are writing a value class that has an obvious natural order, such as alphabetical, numerical, or chronological, you can benefit from it with a little effort, so implement Comparable.

Sample code

public int compareTo(PhoneNumber pn) {
    //Compare area codes
    if (areaCode <pn.areaCode)
        return -1;
    if (areaCode >pn.areaCode)
        return 1;

    //Compare the first half of the area code with the same area code
    if (prefix <pn.prefix)
        return -1;
    if (prefix> pn.prefix)
        return 1;

    //The first half of the area code and the first area code are the same, and the latter half of the area code is compared
    if (lineNumber <pn.lineNumber)
        return -1;
    if (lineNumber >pn.lineNumber)
        return 1;
    
    return 0; // all fields are equal
}