<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ## Chapter 3. Methods Common to All Objects(對象的通用方法) ### Item 14: Consider implementing Comparable(考慮實現 Comparable 接口) Unlike the other methods discussed in this chapter, the compareTo method is not declared in Object. Rather, it is the sole method in the Comparable interface. It is similar in character to Object’s equals method, except that it permits order comparisons in addition to simple equality comparisons, and it is generic. By implementing Comparable, a class indicates that its instances have a natural ordering. Sorting an array of objects that implement Comparable is as simple as this: 與本章討論的其他方法不同,compareTo 方法不是在 Object 中聲明的。相反,它是 Comparable 接口中的唯一方法。它在性質上類似于 Object 的 equals 方法,除了簡單的相等比較之外,它還允許順序比較,而且它是通用的。一個類實現 Comparable,表明實例具有自然順序。對實現 Comparable 的對象數組進行排序非常簡單: ``` Arrays.sort(a); ``` It is similarly easy to search, compute extreme values, and maintain automatically sorted collections of Comparable objects. For example, the following program, which relies on the fact that String implements Comparable, prints an alphabetized list of its command-line arguments with duplicates eliminated: 類似地,搜索、計算極值和維護 Comparable 對象的自動排序集合也很容易。例如,下面的程序依賴于 String 實現 Comparable 這一事實,將命令行參數列表按字母順序打印出來,并消除重復: ``` public class WordList { public static void main(String[] args) { Set<String> s = new TreeSet<>(); Collections.addAll(s, args); System.out.println(s); } } ``` By implementing Comparable, you allow your class to interoperate with all of the many generic algorithms and collection implementations that depend on this interface. You gain a tremendous amount of power for a small amount of effort. Virtually all of the value classes in the Java platform libraries, as well as all enum types (Item 34), implement Comparable. If you are writing a value class with an obvious natural ordering, such as alphabetical order, numerical order, or chronological order, you should implement the Comparable interface: 通過讓類實現 Comparable,就可與依賴于此接口的所有通用算法和集合實現進行互操作。你只需付出一點點努力就能獲得強大的功能。實際上,Java 庫中的所有值類以及所有枚舉類型([Item-34](/Chapter-6/Chapter-6-Item-34-Use-enums-instead-of-int-constants.md))都實現了 Comparable。如果編寫的值類具有明顯的自然順序,如字母順序、數字順序或時間順序,則應實現 Comparable 接口: ``` public interface Comparable<T> { int compareTo(T t); } ``` The general contract of the compareTo method is similar to that of equals: compareTo 方法的一般約定類似于 equals 方法: Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Throws ClassCastException if the specified object’s type prevents it from being compared to this object. 將一個對象與指定的對象進行順序比較。當該對象小于、等于或大于指定對象時,對應返回一個負整數、零或正整數。如果指定對象的類型阻止它與該對象進行比較,則拋出 ClassCastException。 In the following description, the notation sgn(expression) designates the mathematical signum function, which is defined to return -1, 0, or 1,according to whether the value of expression is negative, zero, or positive. 在下面的描述中,`sgn(expression)` 表示數學中的符號函數,它被定義為:根據傳入表達式的值是負數、零或正數,對應返回 -1、0 或 1。 - The implementor must ensure that sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception if and only if y.compareTo(x) throws an exception.) 實現者必須確保所有 x 和 y 滿足 `sgn(x.compareTo(y)) == -sgn(y.compareTo(x))`(這意味著 `x.compareTo(y)` 當且僅當 `y.compareTo(x)` 拋出異常時才拋出異常)。 - The implementor must also ensure that the relation is transitive: (x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0. 實現者還必須確保關系是可傳遞的:`(x.compareTo(y) > 0 && y.compareTo(z) > 0)` 意味著 `x.compareTo(z) > 0`。 - Finally, the implementor must ensure that x.compareTo(y) == 0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)),for all z. 最后,實現者必須確保 `x.compareTo(y) == 0` 時,所有的 z 滿足 `sgn(x.compareTo(z)) == sgn(y.compareTo(z))`。 - It is strongly recommended, but not required, that (x.compareTo(y)== 0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is “Note: This class has a natural ordering that is inconsistent with equals.” 強烈建議 `(x.compareTo(y)== 0) == (x.equals(y))` 成立,但不是必需的。一般來說,任何實現 Comparable 接口并違反此條件的類都應該清楚地注明這一事實。推薦使用的表述是「注意:該類的自然順序與 equals 不一致。」 Don’t be put off by the mathematical nature of this contract. Like the equals contract (Item 10), this contract isn’t as complicated as it looks. Unlike the equals method, which imposes a global equivalence relation on all objects,compareTo doesn’t have to work across objects of different types: when confronted with objects of different types, compareTo is permitted to throw ClassCastException. Usually, that is exactly what it does. The contract does permit intertype comparisons, which are typically defined in an interface implemented by the objects being compared. 不要被這些約定的數學性質所影響。就像 equals 約定([Item-10](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md))一樣,這個約定并不像看起來那么復雜。與 equals 方法不同,equals 方法對所有對象都施加了全局等價關系,compareTo 不需要跨越不同類型的對象工作:當遇到不同類型的對象時,compareTo 允許拋出 ClassCastException。通常,它就是這么做的。該約定確實允許類型間比較,這種比較通常在被比較對象實現的接口中定義。 Just as a class that violates the hashCode contract can break other classes that depend on hashing, a class that violates the compareTo contract can break other classes that depend on comparison. Classes that depend on comparison include the sorted collections TreeSet and TreeMap and the utility classes Collections and Arrays, which contain searching and sorting algorithms. 就像違反 hashCode 約定的類可以破壞依賴 hash 的其他類一樣,違反 compareTo 約定的類也可以破壞依賴 Comparable 的其他類。依賴 Comparable 的類包括排序集合 TreeSet 和 TreeMap,以及實用工具類 Collections 和 Arrays,它們都包含搜索和排序算法。 Let’s go over the provisions of the compareTo contract. The first provision says that if you reverse the direction of a comparison between two object references, the expected thing happens: if the first object is less than the second,then the second must be greater than the first; if the first object is equal to the second, then the second must be equal to the first; and if the first object is greater than the second, then the second must be less than the first. The second provision says that if one object is greater than a second and the second is greater than a third, then the first must be greater than the third. The final provision says that all objects that compare as equal must yield the same results when compared to any other object. 讓我們看一下 compareTo 約定的細節。第一個規定指出,如果你顛倒兩個對象引用之間的比較的方向,就應當發生這樣的情況:如果第一個對象小于第二個對象,那么第二個對象必須大于第一個;如果第一個對象等于第二個對象,那么第二個對象一定等于第一個對象;如果第一個對象大于第二個對象,那么第二個對象一定小于第一個對象。第二個規定指出,如果一個對象大于第二個,第二個大于第三個,那么第一個對象一定大于第三個對象。最后一個規定指出,所有 compareTo 結果為相等的對象分別與任何其他對象相比,必須產生相同的結果。 One consequence of these three provisions is that the equality test imposed by a compareTo method must obey the same restrictions imposed by the equals con-tract: reflexivity, symmetry, and transitivity. Therefore, the same caveat applies: there is no way to extend an instantiable class with a new value component while preserving the compareTo contract, unless you are willing to forgo the benefits of object-oriented abstraction (Item 10). The same workaround applies, too. If you want to add a value component to a class that implements Comparable, don’t extend it; write an unrelated class containing an instance of the first class. Then provide a “view” method that returns the contained instance. This frees you to implement whatever compareTo method you like on the containing class, while allowing its client to view an instance of the containing class as an instance of the contained class when needed. 這三種規定的一個結果是,由 compareTo 方法進行的相等性檢驗必須遵守由 equals 約定進行的相同的限制:反身性、對稱性和傳遞性。因此,同樣的警告也適用于此:除非你愿意放棄面向對象的抽象優點([Item-10](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md)),否則無法在保留 compareTo 約定的同時使用新值組件擴展可實例化類。同樣的解決方案也適用。如果要向實現 Comparable 的類中添加值組件,不要繼承它;編寫一個不相關的類,其中包含第一個類的實例。然后提供返回所包含實例的「視圖」方法。這使你可以自由地在包含類上實現你喜歡的任何 compareTo 方法,同時允許它的客戶端在需要時將包含類的實例視為包含類的實例。 The final paragraph of the compareTo contract, which is a strong suggestion rather than a true requirement, simply states that the equality test imposed by the compareTo method should generally return the same results as the equals method. If this provision is obeyed, the ordering imposed by the compareTo method is said to be consistent with equals. If it’s violated, the ordering is said to be inconsistent with equals. A class whose compareTo method imposes an order that is inconsistent with equals will still work, but sorted collections containing elements of the class may not obey the general contract of the appropriate collection interfaces (Collection, Set, or Map). This is because the general contracts for these interfaces are defined in terms of the equals method, but sorted collections use the equality test imposed by compareTo in place of equals. It is not a catastrophe if this happens, but it’s something to be aware of. compareTo 約定的最后一段是一個強烈的建議,而不是一個真正的要求,它只是簡單地說明了 compareTo 方法所施加的同等性檢驗通常應該與 equals 方法返回相同的結果。如果遵守了這一規定,則 compareTo 方法所施加的排序與 equals 方法一致。如果違反這條建議,那么它的順序就與 equals 不一致。如果一個類的 compareTo 方法強加了一個與 equals 不一致的順序,那么這個類仍然可以工作,但是包含該類元素的有序集合可能無法遵守集合接口(Collection、Set 或 Map)的一般約定。這是因為這些接口的一般約定是根據 equals 方法定義的,但是有序集合使用 compareTo 代替了 equals 實施同等性檢驗。如果發生這種情況,這不是一場災難,但這是需要注意的。 For example, consider the BigDecimal class, whose compareTo method is inconsistent with equals. If you create an empty HashSet instance and then add new BigDecimal("1.0") and new BigDecimal("1.00"),the set will contain two elements because the two BigDecimal instances added to the set are unequal when compared using the equals method. If,however, you perform the same procedure using a TreeSet instead of a HashSet, the set will contain only one element because the two BigDecimal instances are equal when compared using the compareTo method. (See the BigDecimal documentation for details.) 例如,考慮 BigDecimal 類,它的 compareTo 方法與 equals 不一致。如果你創建一個空的 HashSet 實例,然后添加 `new BigDecimal("1.0")` 和 `new BigDecimal("1.00")`,那么該 HashSet 將包含兩個元素,因為添加到該集合的兩個 BigDecimal 實例在使用 equals 方法進行比較時結果是不相等的。但是,如果你使用 TreeSet 而不是 HashSet 執行相同的過程,那么該集合將只包含一個元素,因為使用 compareTo 方法比較兩個 BigDecimal 實例時結果是相等的。(有關詳細信息,請參閱 BigDecimal 文檔。) Writing a compareTo method is similar to writing an equals method, but there are a few key differences. Because the Comparable interface is parameterized, the compareTo method is statically typed, so you don’t need to type check or cast its argument. If the argument is of the wrong type, the invocation won’t even compile. If the argument is null, the invocation should throw a NullPointerException, and it will, as soon as the method attempts to access its members. 編寫 compareTo 方法類似于編寫 equals 方法,但是有一些關鍵的區別。因為 Comparable 接口是參數化的,compareTo 方法是靜態類型的,所以不需要進行類型檢查或強制轉換它的參數。如果參數類型錯誤,則該調用將不能編譯。如果參數為 null,則調用應該拋出 NullPointerException,并且在方法嘗試訪問其成員時拋出該異常。 In a compareTo method, fields are compared for order rather than equality.To compare object reference fields, invoke the compareTo method recursively. If a field does not implement Comparable or you need a nonstandard ordering, use a Comparator instead. You can write your own comparator or use an existing one, as in this compareTo method for CaseInsensitiveString in Item 10: 在 compareTo 方法中,字段是按順序而不是按同等性來比較的。要比較對象引用字段,要遞歸調用 compareTo 方法。如果一個字段沒有實現 Comparable,或者需要一個非標準的排序,那么應使用 Comparator。可以編寫自定義的比較器,或使用現有的比較器,如 [Item-10](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md) 中 CaseInsensitiveString 的 compareTo 方法: ``` // Single-field Comparable with object reference field public final class CaseInsensitiveString implements Comparable<CaseInsensitiveString> { public int compareTo(CaseInsensitiveString cis) { return String.CASE_INSENSITIVE_ORDER.compare(s, cis.s); } ... // Remainder omitted } ``` Note that CaseInsensitiveString implements `Comparable<CaseInsensitiveString>`. This means that a CaseInsensitiveString reference can be compared only to another CaseInsensitiveString reference. This is the normal pattern to follow when declaring a class to implement Comparable. 注意 CaseInsensitiveString 實現了 `Comparable<CaseInsensitiveString>`。這意味著 CaseInsensitiveString 引用只能與另一個 CaseInsensitiveString 引用進行比較。這是在聲明實現 Comparable 的類時要遵循的常規模式。 Prior editions of this book recommended that compareTo methods compare integral primitive fields using the relational operators < and >, and floating point primitive fields using the static methods Double.compare and Float.compare. In Java 7, static compare methods were added to all of Java’s boxed primitive classes. **Use of the relational operators < and > in compareTo methods is verbose and error-prone and no longer recommended.** 本書的舊版本建議 compareTo 方法使用關系運算符 < 和 > 來比較整數基本類型字段,使用靜態方法 `Double.compare` 和 `Float.compare` 來比較浮點基本類型字段。在 Java 7 中,靜態比較方法被添加到所有 Java 的包裝類中。**在 compareTo 方法中使用關系運算符 < 和 > 冗長且容易出錯,因此不再推薦使用。** If a class has multiple significant fields, the order in which you compare them is critical. Start with the most significant field and work your way down. If a comparison results in anything other than zero (which represents equality),you’re done; just return the result. If the most significant field is equal, compare the next-most-significant field, and so on, until you find an unequal field or compare the least significant field. Here is a compareTo method for the PhoneNumber class in Item 11 demonstrating this technique: 如果一個類有多個重要字段,那么比較它們的順序非常關鍵。從最重要的字段開始,一步步往下。如果比較的結果不是 0(用 0 表示相等),那么就完成了;直接返回結果。如果最重要的字段是相等的,就比較下一個最重要的字段,以此類推,直到找到一個不相等的字段或比較到最不重要的字段為止。下面是 [Item-11](/Chapter-3/Chapter-3-Item-11-Always-override-hashCode-when-you-override-equals.md) 中 PhoneNumber 類的 compareTo 方法,演示了這種技術: ``` // Multiple-field Comparable with primitive fields public int compareTo(PhoneNumber pn) { int result = Short.compare(areaCode, pn.areaCode); if (result == 0) { result = Short.compare(prefix, pn.prefix); if (result == 0) result = Short.compare(lineNum, pn.lineNum); } return result; } ``` In Java 8, the Comparator interface was outfitted with a set of comparator construction methods, which enable fluent construction of comparators. These comparators can then be used to implement a compareTo method, as required by the Comparable interface. Many programmers prefer the conciseness of this approach, though it does come at a modest performance cost: sorting arrays of PhoneNumber instances is about 10% slower on my machine. When using this approach, consider using Java’s static import facility so you can refer to static comparator construction methods by their simple names for clarity and brevity. Here’s how the compareTo method for PhoneNumber looks using this approach: 在 Java 8 中,Comparator 接口配備了一組比較器構造方法,可以流暢地構造比較器。然后可以使用這些比較器來實現 Comparator 接口所要求的 compareTo 方法。許多程序員更喜歡這種方法的簡明,盡管它存在一些性能成本:在我的機器上,PhoneNumber 實例的數組排序要慢 10% 左右。在使用這種方法時,請考慮使用 Java 的靜態導入功能,這樣你就可以通過靜態比較器構造方法的簡單名稱來引用它們,以獲得清晰和簡潔。下面是 PhoneNumber 類的 compareTo 方法改進后的樣子: ``` // Comparable with comparator construction methods private static final Comparator<PhoneNumber> COMPARATOR = comparingInt((PhoneNumber pn) -> pn.areaCode) .thenComparingInt(pn -> pn.prefix) .thenComparingInt(pn -> pn.lineNum); public int compareTo(PhoneNumber pn) { return COMPARATOR.compare(this, pn); } ``` **譯注 1:示例代碼默認使用了靜態導入:`import static java.util.Comparator.comparingInt;`** **譯注 2:comparingInt 及 thenComparingInt 的文檔描述** ``` static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) Accepts a function that extracts an int sort key from a type T, and returns a Comparator<T> that compares by that sort key. The returned comparator is serializable if the specified function is also serializable. 接受從類型 T 中提取 int 排序 key 的函數,并返回與該排序 key 進行比較的 Comparator<T>。 如果指定的函數是可序列化的,則返回的比較器也是可序列化的。 Type Parameters: T - the type of element to be compared Parameters: keyExtractor - the function used to extract the integer sort key Returns: a comparator that compares by an extracted key Throws: NullPointerException - if the argument is null Since: 1.8 ``` ``` default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) Returns a lexicographic-order comparator with a function that extracts a int sort key. Implementation Requirements: This default implementation behaves as if thenComparing(comparingInt(keyExtractor)). 返回具有提取 int 排序 key 的函數的字典順序比較器。 實現要求: 此默認實現的行為類似于 thenComparing(comparingInt(keyExtractor))。 Parameters: keyExtractor - the function used to extract the integer sort key Returns: a lexicographic-order comparator composed of this and then the int sort key Throws: NullPointerException - if the argument is null. Since: 1.8 ``` This implementation builds a comparator at class initialization time, using two comparator construction methods. The first is comparingInt. It is a static method that takes a key extractor function that maps an object reference to a key of type int and returns a comparator that orders instances according to that key.In the previous example, comparingInt takes a lambda () that extracts the area code from a PhoneNumber and returns a `Comparator<PhoneNumber>` that orders phone numbers according to their area codes. Note that the lambda explicitly specifies the type of its input parameter (PhoneNumber pn). It turns out that in this situation, Java’s type inference isn’t powerful enough to figure the type out for itself, so we’re forced to help it in order to make the program compile. 這個實現在類初始化時使用兩個比較器構造方法構建一個比較器。第一個是 comparingInt。它是一個靜態方法,接受一個 key 提取器函數,該函數將對象引用映射到 int 類型的 key ,并返回一個比較器,比較器根據該 key 對實例進行排序。在上述的示例中,comparingInt 使用 lambda 表達式從 PhoneNumber 中提取 areaCode,并返回 `Comparator<PhoneNumber>`,按區號來排序電話號碼。注意,lambda 表達式顯式地指定其輸入參數的類型為 PhoneNumber。事實證明,在這種情況下,Java 的類型推斷并沒有強大到足以自己判斷類型,因此我們不得不幫助它來編譯程序。 If two phone numbers have the same area code, we need to further refine the comparison, and that’s exactly what the second comparator construction method,thenComparingInt, does. It is an instance method on Comparator that takes an int key extractor function, and returns a comparator that first applies the original comparator and then uses the extracted key to break ties. You can stack up as many calls to thenComparingInt as you like, resulting in a lexicographic ordering. In the example above, we stack up two calls to thenComparingInt, resulting in an ordering whose secondary key is the prefix and whose tertiary key is the line number. Note that we did not have to specify the parameter type of the key extractor function passed to either of the calls to thenComparingInt: Java’s type inference was smart enough to figure this one out for itself. 如果兩個電話號碼有相同的區號,我們需要進一步改進比較,這正是第二個 comparator 構造方法 thenComparingInt 所做的。它是 Comparator 上的一個實例方法,它接受一個 int 類型的 key 提取函數,并返回一個比較器,該比較器首先應用原始比較器,然后使用提取的 key 來斷開連接。你可以任意堆疊對 thenComparingInt 的調用,從而形成字典順序。在上面的例子中,我們將兩個對 thenComparingInt 的調用疊加起來,得到一個排序,它的第二個 key 是 prefix,而第三個 key 是 lineNum。注意,我們不必指定傳遞給兩個調用 thenComparingInt 的 key 提取器函數的參數類型:Java 的類型推斷足夠智能,可以自行解決這個問題。 The Comparator class has a full complement of construction methods.There are analogues to comparingInt and thenComparingInt for the primitive types long and double. The int versions can also be used for narrower integral types, such as short, as in our PhoneNumber example. The double versions can also be used for float. This provides coverage of all of Java’s numerical primitive types. Comparator 類具有完整的構造方法。對于 long 和 double 的基本類型,有類似 comparingInt 和 thenComparingInt 的方法。int 版本還可以用于范圍更小的整數類型,如 PhoneNumber 示例中的 short。double 版本也可以用于 float。Comparator 類提供的構造方法覆蓋了所有 Java 數值基本類型。 There are also comparator construction methods for object reference types.The static method, named comparing, has two overloadings. One takes a key extractor and uses the keys’ natural order. The second takes both a key extractor and a comparator to be used on the extracted keys. There are three overloadings of the instance method, which is named thenComparing. One overloading takes only a comparator and uses it to provide a secondary order. A second overloading takes only a key extractor and uses the key’s natural order as a secondary order. The final overloading takes both a key extractor and a comparator to be used on the extracted keys. 也有對象引用類型的比較器構造方法。靜態方法名為 compare,它有兩個重載。一個是使用 key 提取器并使用 key 的自然順序。第二種方法同時使用 key 提取器和比較器對提取的 key 進行比較。實例方法有三種重載,稱為 thenComparing。一個重載只需要一個比較器并使用它來提供一個二級順序。第二個重載只接受一個 key 提取器,并將 key 的自然順序用作二級順序。最后的重載需要一個 key 提取器和一個比較器來對提取的 key 進行比較。 Occasionally you may see compareTo or compare methods that rely on the fact that the difference between two values is negative if the first value is less than the second, zero if the two values are equal, and positive if the first value is greater. Here is an example: 有時候,你可能會看到 compareTo 或 compare 方法,它們依賴于以下事實:如果第一個值小于第二個值,則兩個值之間的差為負;如果兩個值相等,則為零;如果第一個值大于零,則為正。下面是一個例子: ``` // BROKEN difference-based comparator - violates transitivity! static Comparator<Object> hashCodeOrder = new Comparator<>() { public int compare(Object o1, Object o2) { return o1.hashCode() - o2.hashCode(); } }; ``` Do not use this technique. It is fraught with danger from integer overflow and IEEE 754 floating point arithmetic artifacts [JLS 15.20.1, 15.21.1]. Furthermore,the resulting methods are unlikely to be significantly faster than those written using the techniques described in this item. Use either a static compare method: 不要使用這種技術。它充滿了來自整數溢出和 IEEE 754 浮點運算構件的危險 [JLS 15.20.1, 15.21.1]。此外,生成的方法不太可能比使用本項目中描述的技術編寫的方法快得多。應使用靜態比較方法: ``` // Comparator based on static compare method static Comparator<Object> hashCodeOrder = new Comparator<>() { public int compare(Object o1, Object o2) { return Integer.compare(o1.hashCode(), o2.hashCode()); } }; ``` or a comparator construction method: 或比較器構造方法: ``` // Comparator based on Comparator construction method static Comparator<Object> hashCodeOrder = Comparator .comparingInt(o -> o.hashCode()); ``` In summary, whenever you implement a value class that has a sensible ordering, you should have the class implement the Comparable interface so that its instances can be easily sorted, searched, and used in comparison-based collections. When comparing field values in the implementations of the compareTo methods, avoid the use of the < and > operators. Instead, use the static compare methods in the boxed primitive classes or the comparator construction methods in the Comparator interface. 總之,無論何時實現具有排序性質的值類,都應該讓類實現 Comparable 接口,這樣就可以輕松地對實例進行排序、搜索,并與依賴于此接口的集合實現進行互操作。在 compareTo 方法的實現中比較字段值時,避免使用 < 和 > 操作符,應使用包裝類中的靜態比較方法或 Comparator 接口中的 comparator 構造方法。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-3/Chapter-3-Introduction.md)** - **Previous Item(上一條目):[Item 13: Override clone judiciously(明智地覆蓋 clone 方法)](/Chapter-3/Chapter-3-Item-13-Override-clone-judiciously.md)** - **Next Item(下一條目):[Chapter 4 Introduction(章節介紹)](/Chapter-4/Chapter-4-Introduction.md)**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看