Valid Java, inclutivejava
When the Comparable interface is implemented, the instance of the class itself has an inherent ordering relationship (natural ordering ).
Therefore, this class can collaborate with many generic algorithms and collections.
The only method we need to implement the Comparable interface --CompareTo.
The following are related rules:
- Sgn (x. compareTo (y) =-sgn (y. compareTo (x ))
- (X. compareTo (y)> 0 & y. compareTo (z)> 0) Then x. compareTo (z)> 0
- X. compareTo (y) = 0 then sgn (x. compareTo (z) = sgn (y. compareTo (z ))
- It is recommended that x. compareTo (y) = 0 x. equals (y)
Article 4 is not necessary, but it is worth understanding.
CompareTo rather than equals may be used for equality comparison in some ordered structures.
In this case, we need to make compareTo and equals compatible.
This is not required in special cases, such as in the BigDecimal class.new BigDecimal("1.00")Andnew BigDecimal("1.0")The equals result is false, and the compareTo result is 0.
Compare different types of fields in a class:
- Relational operators are directly used for non-floating-point basic types.
- Compare method of encapsulation class for floating point type
- The reference type can call compareTo recursively. If Comparable is not implemented for a field, Comparator is displayed.
- The array type applies the above rules to each element.
Generally, for key fields of a class, we can set a priority based on their importance.
Compare the results one by one from the most critical start, and return immediately when a non-zero result is obtained.
The following is an example:
// Making PhoneNumber comparable - Pages 65-66package org.effectivejava.examples.chapter03.item12;import java.util.NavigableSet;import java.util.Random;import java.util.TreeSet;public final class PhoneNumber implements Cloneable, Comparable<PhoneNumber> { private final short areaCode; private final short prefix; private final short lineNumber; public PhoneNumber(int areaCode, int prefix, int lineNumber) { rangeCheck(areaCode, 999, "area code"); rangeCheck(prefix, 999, "prefix"); rangeCheck(lineNumber, 9999, "line number"); this.areaCode = (short) areaCode; this.prefix = (short) prefix; this.lineNumber = (short) lineNumber; } private static void rangeCheck(int arg, int max, String name) { if (arg < 0 || arg > max) throw new IllegalArgumentException(name + ": " + arg); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof PhoneNumber)) return false; PhoneNumber pn = (PhoneNumber) o; return pn.lineNumber == lineNumber && pn.prefix == prefix && pn.areaCode == areaCode; } @Override public int hashCode() { int result = 17; result = 31 * result + areaCode; result = 31 * result + prefix; result = 31 * result + lineNumber; return result; } @Override public PhoneNumber clone() { try { return (PhoneNumber) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } } // Works fine, but can be made faster // public int compareTo(PhoneNumber pn) { // // Compare area codes // if (areaCode < pn.areaCode) // return -1; // if (areaCode > pn.areaCode) // return 1; // // // Area codes are equal, compare prefixes // if (prefix < pn.prefix) // return -1; // if (prefix > pn.prefix) // return 1; // // // Area codes and prefixes are equal, compare line numbers // if (lineNumber < pn.lineNumber) // return -1; // if (lineNumber > pn.lineNumber) // return 1; // // return 0; // All fields are equal // } public int compareTo(PhoneNumber pn) { // Compare area codes int areaCodeDiff = areaCode - pn.areaCode; if (areaCodeDiff != 0) return areaCodeDiff; // Area codes are equal, compare prefixes int prefixDiff = prefix - pn.prefix; if (prefixDiff != 0) return prefixDiff; // Area codes and prefixes are equal, compare line numbers return lineNumber - pn.lineNumber; } public static void main(String[] args) { NavigableSet<PhoneNumber> s = new TreeSet<PhoneNumber>(); for (int i = 0; i < 10; i++) s.add(randomPhoneNumber()); System.out.println(s); } private static final Random rnd = new Random(); private static PhoneNumber randomPhoneNumber() { return new PhoneNumber((short) rnd.nextInt(1000), (short) rnd.nextInt(1000), (short) rnd.nextInt(10000)); }}
The fields in the above example are non-floating point basic types, so the author optimized them.
Since compareTo only requires the return value rather than the size, the difference value is used instead of the logical comparison character.
However, you must note that the field type may not be able to accommodate the difference between two values.
For example Integer. MAX_VALUE-(-1) or Integer. MIN_VALUE-1.
If you can ensure that the field value is not a negative value, this will not happen.