Unlike other methods, the compareTo method is not declared in Object. To be precise, the compareTo method is the only method in the Compareable interface. If you're writing a value class that has a clearly natural order, such as alphabetical, numerical, or chronological, you'll benefit from a little effort, so implement Comparable.
public int compareTo(PhoneNumber pn) {
//Compare area code
if (areaCode < pn.areaCode)
return -1;
if (areaCode > pn.areaCode)
return 1;
//Area code is equal and compares the first half of the city code
if (prefix < pn.prefix)
return -1;
if (prefix > pn.prefix)
return 1;
//The area code and the first half of the city code are equal, and the second half of the city code is compared.
if (lineNumber < pn.lineNumber)
return -1;
if (lineNumber > pn.lineNumber)
return 1;
return 0; //All fields are equal
}
Recommended Posts