## 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)**
- Chapter 2. Creating and Destroying Objects(創建和銷毀對象)
- Item 1: Consider static factory methods instead of constructors(考慮以靜態工廠方法代替構造函數)
- Item 2: Consider a builder when faced with many constructor parameters(在面對多個構造函數參數時,請考慮構建器)
- Item 3: Enforce the singleton property with a private constructor or an enum type(使用私有構造函數或枚舉類型實施單例屬性)
- Item 4: Enforce noninstantiability with a private constructor(用私有構造函數實施不可實例化)
- Item 5: Prefer dependency injection to hardwiring resources(依賴注入優于硬連接資源)
- Item 6: Avoid creating unnecessary objects(避免創建不必要的對象)
- Item 7: Eliminate obsolete object references(排除過時的對象引用)
- Item 8: Avoid finalizers and cleaners(避免使用終結器和清除器)
- Item 9: Prefer try with resources to try finally(使用 try-with-resources 優于 try-finally)
- Chapter 3. Methods Common to All Objects(對象的通用方法)
- Item 10: Obey the general contract when overriding equals(覆蓋 equals 方法時應遵守的約定)
- Item 11: Always override hashCode when you override equals(當覆蓋 equals 方法時,總要覆蓋 hashCode 方法)
- Item 12: Always override toString(始終覆蓋 toString 方法)
- Item 13: Override clone judiciously(明智地覆蓋 clone 方法)
- Item 14: Consider implementing Comparable(考慮實現 Comparable 接口)
- Chapter 4. Classes and Interfaces(類和接口)
- Item 15: Minimize the accessibility of classes and members(盡量減少類和成員的可訪問性)
- Item 16: In public classes use accessor methods not public fields(在公共類中,使用訪問器方法,而不是公共字段)
- Item 17: Minimize mutability(減少可變性)
- Item 18: Favor composition over inheritance(優先選擇復合而不是繼承)
- Item 19: Design and document for inheritance or else prohibit it(繼承要設計良好并且具有文檔,否則禁止使用)
- Item 20: Prefer interfaces to abstract classes(接口優于抽象類)
- Item 21: Design interfaces for posterity(為后代設計接口)
- Item 22: Use interfaces only to define types(接口只用于定義類型)
- Item 23: Prefer class hierarchies to tagged classes(類層次結構優于帶標簽的類)
- Item 24: Favor static member classes over nonstatic(靜態成員類優于非靜態成員類)
- Item 25: Limit source files to a single top level class(源文件僅限有單個頂層類)
- Chapter 5. Generics(泛型)
- Item 26: Do not use raw types(不要使用原始類型)
- Item 27: Eliminate unchecked warnings(消除 unchecked 警告)
- Item 28: Prefer lists to arrays(list 優于數組)
- Item 29: Favor generic types(優先使用泛型)
- Item 30: Favor generic methods(優先使用泛型方法)
- Item 31: Use bounded wildcards to increase API flexibility(使用有界通配符增加 API 的靈活性)
- Item 32: Combine generics and varargs judiciously(明智地合用泛型和可變參數)
- Item 33: Consider typesafe heterogeneous containers(考慮類型安全的異構容器)
- Chapter 6. Enums and Annotations(枚舉和注解)
- Item 34: Use enums instead of int constants(用枚舉類型代替 int 常量)
- Item 35: Use instance fields instead of ordinals(使用實例字段替代序數)
- Item 36: Use EnumSet instead of bit fields(用 EnumSet 替代位字段)
- Item 37: Use EnumMap instead of ordinal indexing(使用 EnumMap 替換序數索引)
- Item 38: Emulate extensible enums with interfaces(使用接口模擬可擴展枚舉)
- Item 39: Prefer annotations to naming patterns(注解優于命名模式)
- Item 40: Consistently use the Override annotation(堅持使用 @Override 注解)
- Item 41: Use marker interfaces to define types(使用標記接口定義類型)
- Chapter 7. Lambdas and Streams(λ 表達式和流)
- Item 42: Prefer lambdas to anonymous classes(λ 表達式優于匿名類)
- Item 43: Prefer method references to lambdas(方法引用優于 λ 表達式)
- Item 44: Favor the use of standard functional interfaces(優先使用標準函數式接口)
- Item 45: Use streams judiciously(明智地使用流)
- Item 46: Prefer side effect free functions in streams(在流中使用無副作用的函數)
- Item 47: Prefer Collection to Stream as a return type(優先選擇 Collection 而不是流作為返回類型)
- Item 48: Use caution when making streams parallel(謹慎使用并行流)
- Chapter 8. Methods(方法)
- Item 49: Check parameters for validity(檢查參數的有效性)
- Item 50: Make defensive copies when needed(在需要時制作防御性副本)
- Item 51: Design method signatures carefully(仔細設計方法簽名)
- Item 52: Use overloading judiciously(明智地使用重載)
- Item 53: Use varargs judiciously(明智地使用可變參數)
- Item 54: Return empty collections or arrays, not nulls(返回空集合或數組,而不是 null)
- Item 55: Return optionals judiciously(明智地的返回 Optional)
- Item 56: Write doc comments for all exposed API elements(為所有公開的 API 元素編寫文檔注釋)
- Chapter 9. General Programming(通用程序設計)
- Item 57: Minimize the scope of local variables(將局部變量的作用域最小化)
- Item 58: Prefer for-each loops to traditional for loops(for-each 循環優于傳統的 for 循環)
- Item 59: Know and use the libraries(了解并使用庫)
- Item 60: Avoid float and double if exact answers are required(若需要精確答案就應避免使用 float 和 double 類型)
- Item 61: Prefer primitive types to boxed primitives(基本數據類型優于包裝類)
- Item 62: Avoid strings where other types are more appropriate(其他類型更合適時應避免使用字符串)
- Item 63: Beware the performance of string concatenation(當心字符串連接引起的性能問題)
- Item 64: Refer to objects by their interfaces(通過接口引用對象)
- Item 65: Prefer interfaces to reflection(接口優于反射)
- Item 66: Use native methods judiciously(明智地使用本地方法)
- Item 67: Optimize judiciously(明智地進行優化)
- Item 68: Adhere to generally accepted naming conventions(遵守被廣泛認可的命名約定)
- Chapter 10. Exceptions(異常)
- Item 69: Use exceptions only for exceptional conditions(僅在確有異常條件下使用異常)
- Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors(對可恢復情況使用 checked 異常,對編程錯誤使用運行時異常)
- Item 71: Avoid unnecessary use of checked exceptions(避免不必要地使用 checked 異常)
- Item 72: Favor the use of standard exceptions(鼓勵復用標準異常)
- Item 73: Throw exceptions appropriate to the abstraction(拋出能用抽象解釋的異常)
- Item 74: Document all exceptions thrown by each method(為每個方法記錄會拋出的所有異常)
- Item 75: Include failure capture information in detail messages(異常詳細消息中應包含捕獲失敗的信息)
- Item 76: Strive for failure atomicity(盡力保證故障原子性)
- Item 77: Don’t ignore exceptions(不要忽略異常)
- Chapter 11. Concurrency(并發)
- Item 78: Synchronize access to shared mutable data(對共享可變數據的同步訪問)
- Item 79: Avoid excessive synchronization(避免過度同步)
- Item 80: Prefer executors, tasks, and streams to threads(Executor、task、流優于直接使用線程)
- Item 81: Prefer concurrency utilities to wait and notify(并發實用工具優于 wait 和 notify)
- Item 82: Document thread safety(文檔應包含線程安全屬性)
- Item 83: Use lazy initialization judiciously(明智地使用延遲初始化)
- Item 84: Don’t depend on the thread scheduler(不要依賴線程調度器)
- Chapter 12. Serialization(序列化)
- Item 85: Prefer alternatives to Java serialization(優先選擇 Java 序列化的替代方案)
- Item 86: Implement Serializable with great caution(非常謹慎地實現 Serializable)
- Item 87: Consider using a custom serialized form(考慮使用自定義序列化形式)
- Item 88: Write readObject methods defensively(防御性地編寫 readObject 方法)
- Item 89: For instance control, prefer enum types to readResolve(對于實例控制,枚舉類型優于 readResolve)
- Item 90: Consider serialization proxies instead of serialized instances(考慮以序列化代理代替序列化實例)