<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                ## Chapter 3. Methods Common to All Objects(對象的通用方法) ### Item 11: Always override hashCode when you override equals(當覆蓋 equals 方法時,總要覆蓋 hashCode 方法) **You must override hashCode in every class that overrides equals.** If you fail to do so, your class will violate the general contract for hashCode, which will prevent it from functioning properly in collections such as HashMap and HashSet. Here is the contract, adapted from the Object specification: **在覆蓋了 equals 方法的類中,必須覆蓋 hashCode 方法。** 如果你沒有這樣做,該類將違反 hashCode 方法的一般約定,這將阻止該類在 HashMap 和 HashSet 等集合中正常運行。以下是根據 Object 規范修改的約定: - When the hashCode method is invoked on an object repeatedly during an execution of an application, it must consistently return the same value, provided no information used in equals comparisons is modified. This value need not remain consistent from one execution of an application to another. 應用程序執行期間對對象重復調用 hashCode 方法時,它必須一致地返回相同的值,前提是不對 equals 方法中用于比較的信息進行修改。這個值不需要在應用程序的不同執行之間保持一致。 - If two objects are equal according to the equals(Object) method, then calling hashCode on the two objects must produce the same integer result. 如果根據 `equals(Object)` 方法判斷出兩個對象是相等的,那么在兩個對象上調用 hashCode 方法必須產生相同的整數結果。 - If two objects are unequal according to the equals(Object) method, it is not required that calling hashCode on each of the objects must produce distinct results. However, the programmer should be aware that producing distinct results for unequal objects may improve the performance of hash tables. 如果根據 `equals(Object)` 方法判斷出兩個對象不相等,則不需要在每個對象上調用 hashCode 方法時必須產生不同的結果。但是,程序員應該知道,為不相等的對象生成不同的結果可能會提高散列表的性能。 **The key provision that is violated when you fail to override hashCode is the second one: equal objects must have equal hash codes.** Two distinct instances may be logically equal according to a class’s equals method, but to Object’s hashCode method, they’re just two objects with nothing much in common. Therefore, Object’s hashCode method returns two seemingly random numbers instead of two equal numbers as required by the contract.For example, suppose you attempt to use instances of the PhoneNumber class from Item 10 as keys in a HashMap: **當你無法覆蓋 hashCode 方法時,將違反第二個關鍵條款:相等的對象必須具有相等的散列碼。** 根據類的 equals 方法,兩個不同的實例在邏輯上可能是相等的,但是對于對象的 hashCode 方法來說,它們只是兩個沒有共同之處的對象。因此,Object 的 hashCode 方法返回兩個看似隨機的數字,而不是約定要求的兩個相等的數字。例如,假設你嘗試使用[Item-10](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md)中的 PhoneNumber 類實例作為 HashMap 中的鍵: ``` Map<PhoneNumber, String> m = new HashMap<>(); m.put(new PhoneNumber(707, 867, 5309), "Jenny"); ``` At this point, you might expect m.get(new PhoneNumber(707, 867, 5309)) to return "Jenny", but instead, it returns null. Notice that two PhoneNumber instances are involved: one is used for insertion into the HashMap, and a second, equal instance is used for (attempted) retrieval. The PhoneNumber class’s failure to override hashCode causes the two equal instances to have unequal hash codes, in violation of the hashCode contract.Therefore, the get method is likely to look for the phone number in a different hash bucket from the one in which it was stored by the put method. Even if the two instances happen to hash to the same bucket, the get method will almost certainly return null, because HashMap has an optimization that caches the hash code associated with each entry and doesn’t bother checking for object equality if the hash codes don’t match. 此時,你可能期望 `m.get(new PhoneNumber(707, 867,5309))` 返回「Jenny」,但是它返回 null。注意,這里涉及到兩個 PhoneNumber 實例:一個用于插入到 HashMap 中,另一個相等的實例(被試圖)用于檢索。由于 PhoneNumber 類未能覆蓋 hashCode 方法,導致兩個相等的實例具有不相等的散列碼,這違反了 hashCode 方法約定。因此,get 方法查找電話號碼的散列桶可能會與 put 方法存儲電話號碼的散列桶不同。即使這兩個實例碰巧分配在同一個散列桶上,get 方法幾乎肯定會返回 null,因為 HashMap 有一個優化,它緩存每個條目相關聯的散列碼,如果散列碼不匹配,就不會檢查對象是否相等。 Fixing this problem is as simple as writing a proper hashCode method for PhoneNumber. So what should a hashCode method look like? It’s trivial to write a bad one. This one, for example, is always legal but should never be used: 解決這個問題就像為 PhoneNumber 編寫一個正確的 hashCode 方法一樣簡單。那么 hashCode 方法應該是什么樣的呢?寫一個反面例子很容易。例如,以下方法是合法的,但是不應該被使用: ``` // The worst possible legal hashCode implementation - never use! @Override public int hashCode() { return 42; } ``` It’s legal because it ensures that equal objects have the same hash code. It’s atrocious because it ensures that every object has the same hash code. Therefore,every object hashes to the same bucket, and hash tables degenerate to linked lists. Programs that should run in linear time instead run in quadratic time. For large hash tables, this is the difference between working and not working. 它是合法的,因為它確保了相等的對象具有相同的散列碼。同時它也很糟糕,因為它使每個對象都有相同的散列碼。因此,每個對象都分配到同一個桶中,散列表退化為鏈表。這樣,原本應該在線性階 `O(n)` 運行的程序將在平方階 `O(n^2)` 運行。對于大型散列表,這是工作和不工作的區別。 A good hash function tends to produce unequal hash codes for unequal instances. This is exactly what is meant by the third part of the hashCode contract. Ideally, a hash function should distribute any reasonable collection of unequal instances uniformly across all int values. Achieving this ideal can be difficult. Luckily it’s not too hard to achieve a fair approximation. Here is a simple recipe: 一個好的散列算法傾向于為不相等的實例生成不相等的散列碼。這正是 hashCode 方法約定第三部分的含義。理想情況下,一個散列算法應該在所有 int 值上均勻合理分布所有不相等實例集合。實現這個理想是很困難的。幸運的是,實現一個類似的并不太難。這里有一個簡單的方式: 1、Declare an int variable named result, and initialize it to the hash code c for the first significant field in your object, as computed in step 2.a. (Recall from Item 10 that a significant field is a field that affects equals comparisons.) 聲明一個名為 result 的 int 變量,并將其初始化為對象中第一個重要字段的散列碼 c,如步驟 2.a 中計算的那樣。(回想一下 [Item-10](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md) 中的重要字段會對比較產生影響) 2、For every remaining significant field f in your object, do the following: 對象中剩余的重要字段 f,執行以下操作: a. Compute an int hash code c for the field: 為字段計算一個整數散列碼 c: i. If the field is of a primitive type, compute Type.hashCode(f),where Type is the boxed primitive class corresponding to f’s type. 如果字段是基本數據類型,計算 `Type.hashCode(f)`,其中 type 是與 f 類型對應的包裝類。 ii. If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison is required,compute a “canonical representation” for this field and invoke hashCode on the canonical representation. If the value of the field is null, use 0 (or some other constant, but 0 is traditional). 如果字段是對象引用,并且該類的 equals 方法通過遞歸調用 equals 方法來比較字段,則遞歸調用字段上的 hashCode 方法。如果需要更復雜的比較,則為該字段計算一個「canonical representation」,并在 canonical representation 上調用 hashCode 方法。如果字段的值為空,則使用 0(或其他常數,但 0 是慣用的)。 iii. If the field is an array, treat it as if each significant element were a separate field. That is, compute a hash code for each significant element by applying these rules recursively, and combine the values per step 2.b. If the array has no significant elements, use a constant, preferably not 0. If all elements are significant, use Arrays.hashCode. 如果字段是一個數組,則將其每個重要元素都視為一個單獨的字段。也就是說,通過遞歸地應用這些規則計算每個重要元素的散列碼,并將每個步驟 2.b 的值組合起來。如果數組中沒有重要元素,則使用常量,最好不是 0。如果所有元素都很重要,那么使用 `Arrays.hashCode`。 b. Combine the hash code c computed in step 2.a into result as follows: 將步驟 2.a 中計算的散列碼 c 合并到 result 變量,如下所示: ``` result = 31 * result + c; ``` 3、Return result. 返回 result 變量。 When you are finished writing the hashCode method, ask yourself whether equal instances have equal hash codes. Write unit tests to verify your intuition (unless you used AutoValue to generate your equals and hashCode methods,in which case you can safely omit these tests). If equal instances have unequal hash codes, figure out why and fix the problem. 當你完成了 hashCode 方法的編寫之后,問問自己現在相同的實例是否具有相同的散列碼。編寫單元測試來驗證你的直覺(除非你使用 AutoValue 生成你的 equals 方法和 hashCode 方法,在這種情況下你可以安全地省略這些測試)。如果相同的實例有不相等的散列碼,找出原因并修復問題。 You may exclude derived fields from the hash code computation. In other words, you may ignore any field whose value can be computed from fields included in the computation. You must exclude any fields that are not used in equals comparisons, or you risk violating the second provision of the hashCode contract. 可以從散列碼計算中排除派生字段。換句話說,你可以忽略任何可以從包含的字段計算其值的字段。你必須排除不用 `equals` 比較的任何字段,否則你可能會違反 hashCode 方法約定的第二個條款。 The multiplication in step 2.b makes the result depend on the order of the fields, yielding a much better hash function if the class has multiple similar fields. For example, if the multiplication were omitted from a String hash function, all anagrams would have identical hash codes. The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, because multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance on some architectures: 31 \* i == (i <<5) - i. Modern VMs do this sort of optimization automatically. 在步驟 2.b 中使用的乘法將使結果取決于字段的順序,如果類有多個相似的字段,則會產生一個更好的散列算法。例如,如果字符串散列算法中省略了乘法,那么所有的字母順序都有相同的散列碼。選擇 31 是因為它是奇素數。如果是偶數,乘法運算就會溢出,信息就會丟失,因為乘法運算等同于移位。使用素數的好處不太明顯,但它是傳統用法。31 有一個很好的特性,可以用移位和減法來代替乘法,從而在某些體系結構上獲得更好的性能:`31 * i == (i <<5) – i`。現代虛擬機自動進行這種優化。 Let’s apply the previous recipe to the PhoneNumber class: 讓我們將前面的方法應用到 PhoneNumber 類: ``` // Typical hashCode method @Override public int hashCode() { int result = Short.hashCode(areaCode); result = 31 * result + Short.hashCode(prefix); result = 31 * result + Short.hashCode(lineNum); return result; } ``` Because this method returns the result of a simple deterministic computation whose only inputs are the three significant fields in a PhoneNumber instance,it is clear that equal PhoneNumber instances have equal hash codes. This method is, in fact, a perfectly good hashCode implementation for PhoneNumber, on par with those in the Java platform libraries. It is simple, is reasonably fast, and does a reasonable job of dispersing unequal phone numbers into different hash buckets. 因為這個方法返回一個簡單的確定的計算結果,它的唯一輸入是 PhoneNumber 實例中的三個重要字段,所以很明顯,相等的 PhoneNumber 實例具有相等的散列碼。實際上,這個方法是 PhoneNumber 的一個非常好的 hashCode 方法實現,與 Java 庫中的 hashCode 方法實現相當。它很簡單,速度也相當快,并且合理地將不相等的電話號碼分散到不同的散列桶中。 While the recipe in this item yields reasonably good hash functions, they are not state-of-the-art. They are comparable in quality to the hash functions found in the Java platform libraries’ value types and are adequate for most uses. If you have a bona fide need for hash functions less likely to produce collisions, see Guava’s com.google.common.hash.Hashing [Guava]. 雖然本條目中的方法產生了相當不錯的散列算法,但它們并不是最先進的。它們的質量可與 Java 庫的值類型中的散列算法相媲美,對于大多數用途來說都是足夠的。如果你確實需要不太可能產生沖突的散列算法,請參閱 Guava 的 com.google.common.hash.Hashing [Guava]。 The Objects class has a static method that takes an arbitrary number of objects and returns a hash code for them. This method, named hash, lets you write one-line hashCode methods whose quality is comparable to those written according to the recipe in this item. Unfortunately, they run more slowly because they entail array creation to pass a variable number of arguments, as well as boxing and unboxing if any of the arguments are of primitive type. This style of hash function is recommended for use only in situations where performance is not critical. Here is a hash function for PhoneNumber written using this technique: Objects 類有一個靜態方法,它接受任意數量的對象并返回它們的散列碼。這個名為 `hash` 的方法允許你編寫只有一行代碼的 hashCode 方法,這些方法的質量可以與本條目中提供的編寫方法媲美。不幸的是,它們運行得更慢,因為它們需要創建數組來傳遞可變數量的參數,如果任何參數是原始類型的,則需要進行裝箱和拆箱。推薦只在性能不重要的情況下使用這種散列算法。下面是使用這種技術編寫的 PhoneNumber 的散列算法: ``` // One-line hashCode method - mediocre performance @Override public int hashCode() { return Objects.hash(lineNum, prefix, areaCode); } ``` If a class is immutable and the cost of computing the hash code is significant,you might consider caching the hash code in the object rather than recalculating it each time it is requested. If you believe that most objects of this type will be used as hash keys, then you should calculate the hash code when the instance is created. Otherwise, you might choose to lazily initialize the hash code the first time hash-Code is invoked. Some care is required to ensure that the class remains thread-safe in the presence of a lazily initialized field (Item 83). Our PhoneNumber class does not merit this treatment, but just to show you how it’s done, here it is. Note that the initial value for the hashCode field (in this case, 0) should not be the hash code of a commonly created instance: 如果一個類是不可變的,并且計算散列碼的成本非常高,那么你可以考慮在對象中緩存散列碼,而不是在每次請求時重新計算它。如果你認為這種類型的大多數對象都將用作散列鍵,那么你應該在創建實例時計算散列碼。否則,你可以選擇在第一次調用 hashCode 方法時延遲初始化散列碼。在一個延遲初始化的字段([Item-83](/Chapter-11/Chapter-11-Item-83-Use-lazy-initialization-judiciously.md))的情況下,需要注意以確保該類仍然是線程安全的。我們的 PhoneNumber 類不值得進行這種處理,但只是為了向你展示它是如何實現的,如下所示。注意,散列字段的初始值(在本例中為 0)不應該是通常創建的實例的散列碼: ``` // hashCode method with lazily initialized cached hash code private int hashCode; // Automatically initialized to 0 @Override public int hashCode() { int result = hashCode; if (result == 0) { result = Short.hashCode(areaCode); result = 31 * result + Short.hashCode(prefix); result = 31 * result + Short.hashCode(lineNum); hashCode = result; } return result; } ``` **Do not be tempted to exclude significant fields from the hash code computation to improve performance.** While the resulting hash function may run faster, its poor quality may degrade hash tables’ performance to the point where they become unusable. In particular, the hash function may be confronted with a large collection of instances that differ mainly in regions you’ve chosen to ignore. If this happens, the hash function will map all these instances to a few hash codes, and programs that should run in linear time will instead run in quadratic time. **不要試圖從散列碼計算中排除重要字段,以提高性能。** 雖然得到的散列算法可能運行得更快,但其糟糕的質量可能會將散列表的性能降低到無法使用的程度。特別是,散列算法可能會遇到大量實例,這些實例在你選擇忽略的不同區域。如果發生這種情況,散列算法將把所有這些實例映射很少一部分散列碼,使得原本應該在線性階 `O(n)` 運行的程序將在平方階 `O(n^2)` 運行。 This is not just a theoretical problem. Prior to Java 2, the String hash function used at most sixteen characters evenly spaced throughout the string,starting with the first character. For large collections of hierarchical names, such as URLs, this function displayed exactly the pathological behavior described earlier. 這不僅僅是一個理論問題。在 Java 2 之前,字符串散列算法在字符串中,以第一個字符開始,最多使用 16 個字符。對于大量且分層次的集合(如 url),該函數完全展示了前面描述的病態行為。 **Don’t provide a detailed specification for the value returned by hashCode, so clients can’t reasonably depend on it; this gives you the flexibility to change it.** Many classes in the Java libraries, such as String and Integer, specify the exact value returned by their hashCode method as a function of the instance value. This is not a good idea but a mistake that we’re forced to live with: It impedes the ability to improve the hash function in future releases. If you leave the details unspecified and a flaw is found in the hash function or a better hash function is discovered, you can change it in a subsequent release. **不要為 hashCode 返回的值提供詳細的規范,這樣客戶端就不能理所應當的依賴它。這(也)給了你更改它的余地。** Java 庫中的許多類,例如 String 和 Integer,都將 hashCode 方法返回的確切值指定為實例值的函數。這不是一個好主意,而是一個我們不得不面對的錯誤:它阻礙了在未來版本中提高散列算法的能力。如果你保留了未指定的細節,并且在散列算法中發現了缺陷,或者發現了更好的散列算法,那么你可以在后續版本中更改它。 In summary, you must override hashCode every time you override equals,or your program will not run correctly. Your hashCode method must obey the general contract specified in Object and must do a reasonable job assigning unequal hash codes to unequal instances. This is easy to achieve, if slightly tedious, using the recipe on page 51. As mentioned in Item 10, the AutoValue framework provides a fine alternative to writing equals and hashCode methods manually, and IDEs also provide some of this functionality. 總之,每次覆蓋 equals 方法時都必須覆蓋 hashCode 方法,否則程序將無法正確運行。你的 hashCode 方法必須遵守 Object 中指定的通用約定,并且必須合理地將不相等的散列碼分配給不相等的實例。這很容易實現,如果有點枯燥,可使用第 51 頁的方法。如 [Item-10](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md) 所述,AutoValue 框架提供了一種能很好的替代手動編寫 equals 方法和 hashCode 方法的功能,IDE 也提供了這種功能。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-3/Chapter-3-Introduction.md)** - **Previous Item(上一條目):[Item 10: Obey the general contract when overriding equals(覆蓋 equals 方法時應遵守的約定)](/Chapter-3/Chapter-3-Item-10-Obey-the-general-contract-when-overriding-equals.md)** - **Next Item(下一條目):[Item 12: Always override toString(始終覆蓋 toString 方法)](/Chapter-3/Chapter-3-Item-12-Always-override-toString.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>

                              哎呀哎呀视频在线观看