## Chapter 5. Generics(泛型)
### Item 26: Don’t use raw types(不要使用原始類型)
First, a few terms. A class or interface whose declaration has one or more type parameters is a generic class or interface [JLS, 8.1.2, 9.1.2]. For example, the List interface has a single type parameter, E, representing its element type. The full name of the interface is `List<E>` (read “list of E”), but people often call it List for short. Generic classes and interfaces are collectively known as generic types.
首先,介紹一些術語。聲明中具有一個或多個類型參數的類或接口就是泛型類或泛型接口 [JLS, 8.1.2, 9.1.2]。例如,List 接口有一個類型參數 E,用于表示其元素類型。該接口的全名是 `List<E>`(讀作「List of E」),但人們通常簡稱為 List。泛型類和泛型接口統稱為泛型。
Each generic type defines a set of parameterized types, which consist of the class or interface name followed by an angle-bracketed list of actual type parameters corresponding to the generic type’s formal type parameters [JLS, 4.4, 4.5]. For example, `List<String>` (read “list of string”) is a parameterized type representing a list whose elements are of type String. (String is the actual type parameter corresponding to the formal type parameter E.)
每個泛型定義了一組參數化類型,這些參數化類型包括類名或接口名,以及帶尖括號的參數列表,參數列表是與泛型的形式類型參數相對應的實際類型 [JLS, 4.4, 4.5]。例如,`List<String>`(讀作「List of String」)是一個參數化類型,表示元素類型為 String 類型的 List。(String 是與形式類型參數 E 對應的實際類型參數。)
Finally, each generic type defines a raw type, which is the name of the generic type used without any accompanying type parameters [JLS, 4.8]. For example, the raw type corresponding to `List<E>` is List. Raw types behave as if all of the generic type information were erased from the type declaration. They exist primarily for compatibility with pre-generics code.
最后,每個泛型都定義了一個原始類型,它是沒有任何相關類型參數的泛型的名稱 [JLS, 4.8]。例如,`List<E>` 對應的原始類型是 List。原始類型的行為就好像所有泛型信息都從類型聲明中刪除了一樣。它們的存在主要是為了與之前的泛型代碼兼容。
Before generics were added to Java, this would have been an exemplary collection declaration. As of Java 9, it is still legal, but far from exemplary:
在將泛型添加到 Java 之前,這是一個典型的集合聲明。就 Java 9 而言,它仍然是合法的,但不應效仿:
```
// Raw collection type - don't do this!
// My stamp collection. Contains only Stamp instances.
private final Collection stamps = ... ;
```
If you use this declaration today and then accidentally put a coin into your stamp collection, the erroneous insertion compiles and runs without error (though the compiler does emit a vague warning):
如果你今天使用這個聲明,然后意外地將 coin 放入 stamp 集合中,這一錯誤的插入依然能夠編譯并沒有錯誤地運行(盡管編譯器確實發出了模糊的警告):
```
// Erroneous insertion of coin into stamp collection
stamps.add(new Coin( ... )); // Emits "unchecked call" warning
```
You don’t get an error until you try to retrieve the coin from the stamp collection:
直到從 stamp 集合中獲取 coin 時才會收到錯誤提示:
```
// Raw iterator type - don't do this!
for (Iterator i = stamps.iterator(); i.hasNext(); )
Stamp stamp = (Stamp) i.next(); // Throws ClassCastException
stamp.cancel();
```
As mentioned throughout this book, it pays to discover errors as soon as possible after they are made, ideally at compile time. In this case, you don’t discover the error until runtime, long after it has happened, and in code that may be distant from the code containing the error. Once you see the ClassCastException, you have to search through the codebase looking for the method invocation that put the coin into the stamp collection. The compiler can’t help you, because it can’t understand the comment that says, “Contains only Stamp instances.”
正如在本書中提到的,在出現錯誤之后盡快發現錯誤是有價值的,最好是在編譯時。在本例這種情況下,直到運行時(在錯誤發生很久之后)才發現錯誤,而且報錯代碼可能與包含錯誤的代碼相距很遠。一旦看到 ClassCastException,就必須在代碼中搜索將 coin 放進 stamp 集合的方法調用。編譯器不能幫助你,因為它不能理解注釋「Contains only Stamp instances.」
With generics, the type declaration contains the information, not the comment:
對于泛型,類型聲明應該包含類型信息,而不是注釋:
```
// Parameterized collection type - typesafe
private final Collection<Stamp> stamps = ... ;
```
From this declaration, the compiler knows that stamps should contain only Stamp instances and guarantees it to be true, assuming your entire codebase compiles without emitting (or suppressing; see Item 27) any warnings. When stamps is declared with a parameterized type declaration, the erroneous insertion generates a compile-time error message that tells you exactly what is wrong:
從這個聲明看出,編譯器應該知道 stamps 應該只包含 Stamp 實例,為保證它確實如此,假設你的整個代碼庫編譯沒有發出(或抑制;詳見 [Item-27](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md))任何警告。當 stamps 利用一個參數化的類型進行聲明時,錯誤的插入將生成編譯時錯誤消息,該消息將確切地告訴你哪里出了問題:
```
Test.java:9: error: incompatible types: Coin cannot be converted
to Stamp
c.add(new Coin());
^
```
The compiler inserts invisible casts for you when retrieving elements from collections and guarantees that they won’t fail (assuming, again, that all of your code did not generate or suppress any compiler warnings). While the prospect of accidentally inserting a coin into a stamp collection may appear far-fetched, the problem is real. For example, it is easy to imagine putting a BigInteger into a collection that is supposed to contain only BigDecimal instances.
當從集合中檢索元素時,編譯器會為你執行不可見的強制類型轉換,并確保它們不會失敗(再次假設你的所有代碼沒有產生或抑制任何編譯器警告)。雖然不小心將 coin 插入 stamps 集合看起來有些牽強,但這類問題是真實存在的。例如,很容易想象將一個 BigInteger 放入一個只包含 BigDecimal 實例的集合中。
As noted earlier, it is legal to use raw types (generic types without their type parameters), but you should never do it. **If you use raw types, you lose all the safety and expressiveness benefits of generics.** Given that you shouldn’t use them, why did the language designers permit raw types in the first place? For compatibility. Java was about to enter its second decade when generics were added, and there was an enormous amount of code in existence that did not use generics. It was deemed critical that all of this code remain legal and interoperate with newer code that does use generics. It had to be legal to pass instances of parameterized types to methods that were designed for use with raw types, and vice versa. This requirement, known as migration compatibility, drove the decisions to support raw types and to implement generics using erasure (Item 28).
如前所述,使用原始類型(沒有類型參數的泛型)是合法的,但是你永遠不應該這樣做。**如果使用原始類型,就會失去泛型的安全性和表現力。** 既然你不應該使用它們,那么為什么語言設計者一開始就允許原始類型呢?答案是:為了兼容性。Java 即將進入第二個十年,泛型被添加進來時,還存在大量不使用泛型的代碼。保持所有這些代碼合法并與使用泛型的新代碼兼容被認為是關鍵的。將參數化類型的實例傳遞給設計用于原始類型的方法必須是合法的,反之亦然。這被稱為遷移兼容性的需求,它促使原始類型得到支持并使用擦除實現泛型 ([Item-28](/Chapter-5/Chapter-5-Item-28-Prefer-lists-to-arrays.md))。
While you shouldn’t use raw types such as List, it is fine to use types that are parameterized to allow insertion of arbitrary objects, such as `List<Object>`. Just what is the difference between the raw type List and the parameterized type `List<Object>`? Loosely speaking, the former has opted out of the generic type system, while the latter has explicitly told the compiler that it is capable of holding objects of any type. While you can pass a `List<String>` to a parameter of type List, you can’t pass it to a parameter of type `List<Object>`. There are sub-typing rules for generics, and `List<String>` is a subtype of the raw type List, but not of the parameterized type `List<Object>` (Item 28). As a consequence, **you lose type safety if you use a raw type such as List, but not if you use a parameterized type such as List<Object>.**
雖然你不應該使用原始類型(如 List),但是可以使用參數化的類型來允許插入任意對象,如 `List<Object>`。原始類型 List 和參數化類型 `List<Object>` 之間的區別是什么?粗略地說,前者選擇了不使用泛型系統,而后者明確地告訴編譯器它能夠保存任何類型的對象。雖然可以將 `List<String>` 傳遞給 List 類型的參數,但不能將其傳遞給類型 `List<Object>` 的參數。泛型有子類型規則,`List<String>` 是原始類型 List 的子類型,而不是參數化類型 `List<Object>` 的子類型([Item-28](/Chapter-5/Chapter-5-Item-28-Prefer-lists-to-arrays.md))。因此,**如果使用原始類型(如 List),就會失去類型安全性,但如果使用參數化類型(如 `List<Object>`)則不會。**
To make this concrete, consider the following program:
為了使這一點具體些,考慮下面的程序:
```
// Fails at runtime - unsafeAdd method uses a raw type (List)!
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
unsafeAdd(strings, Integer.valueOf(42));
String s = strings.get(0); // Has compiler-generated cast
}
private static void unsafeAdd(List list, Object o) {
list.add(o);
}
```
This program compiles, but because it uses the raw type List, you get a warning:
該程序可以編譯,但因為它使用原始類型 List,所以你會得到一個警告:
```
Test.java:10: warning: [unchecked] unchecked call to add(E) as a
member of the raw type List
list.add(o);
^
```
And indeed, if you run the program, you get a ClassCastException when the program tries to cast the result of the invocation strings.get(0), which is an Integer, to a String. This is a compiler-generated cast, so it’s normally guaranteed to succeed, but in this case we ignored a compiler warning and paid the price.
實際上,如果你運行程序,當程序試圖將調用 `strings.get(0)` 的結果強制轉換為字符串時,你會得到一個 ClassCastException。這是一個由編譯器生成的強制類型轉換,它通常都能成功,但在本例中,我們忽略了編譯器的警告,并為此付出了代價。
If you replace the raw type List with the parameterized type `List<Object>` in the unsafeAdd declaration and try to recompile the program, you’ll find that it no longer compiles but emits the error message:
如果將 unsafeAdd 聲明中的原始類型 List 替換為參數化類型 `List<Object>`,并嘗試重新編譯程序,你會發現它不再編譯,而是發出錯誤消息:
```
Test.java:5: error: incompatible types: List<String> cannot be
converted to List<Object>
unsafeAdd(strings, Integer.valueOf(42));
^
```
You might be tempted to use a raw type for a collection whose element type is unknown and doesn’t matter. For example, suppose you want to write a method that takes two sets and returns the number of elements they have in common. Here’s how you might write such a method if you were new to generics:
對于元素類型未知且無關緊要的集合,你可能會嘗試使用原始類型。例如,假設你希望編寫一個方法,該方法接受兩個集合并返回它們共有的元素數量。如果你是使用泛型的新手,那么你可以這樣編寫一個方法:
```
// Use of raw type for unknown element type - don't do this!
static int numElementsInCommon(Set s1, Set s2) {
int result = 0;
for (Object o1 : s1)
if (s2.contains(o1))
result++;
return result;
}
```
This method works but it uses raw types, which are dangerous. The safe alternative is to use unbounded wildcard types. If you want to use a generic type but you don’t know or care what the actual type parameter is, you can use a question mark instead. For example, the unbounded wildcard type for the generic type `Set<E>` is `Set<?>` (read “set of some type”). It is the most general parameterized Set type, capable of holding any set. Here is how the numElementsInCommon declaration looks with unbounded wildcard types:
這種方法是可行的,但是它使用的是原始類型,這是很危險的。安全的替代方法是使用無界通配符類型。如果你想使用泛型,但不知道或不關心實際的類型參數是什么,那么可以使用問號代替。例如,泛型集 `Set<E>` 的無界通配符類型是 `Set<?>`(讀作「set of some type」)。它是最通用的參數化集合類型,能夠容納任何集合:
```
// Uses unbounded wildcard type - typesafe and flexible
static int numElementsInCommon(Set<?> s1, Set<?> s2) { ... }
```
What is the difference between the unbounded wildcard type `Set<?>` and the raw type Set? Does the question mark really buy you anything? Not to belabor the point, but the wildcard type is safe and the raw type isn’t. You can put any element into a collection with a raw type, easily corrupting the collection’s type invariant (as demonstrated by the unsafeAdd method on page 119); you can’t put any element (other than null) into a `Collection<?>`. Attempting to do so will generate a compile-time error message like this:
無界通配符類型 `Set<?>` 和原始類型 Set 之間的區別是什么?問號真的能起作用嗎?我并不是在強調這一點,但是通配符類型是安全的,而原始類型則不是。將任何元素放入具有原始類型的集合中,很容易破壞集合的類型一致性(如上述的 unsafeAdd 方法所示);你不能將任何元素(除了 null)放入 `Collection<?>`。嘗試這樣做將生成這樣的編譯時錯誤消息:
```
WildCard.java:13: error: incompatible types: String cannot be converted to CAP#1
c.add("verboten");
^ where CAP#1
is a fresh type-variable:
CAP#1 extends Object from capture of ?
```
Admittedly this error message leaves something to be desired, but the compiler has done its job, preventing you from corrupting the collection’s type invariant, whatever its element type may be. Not only can’t you put any element (other than null) into a `Collection<?>`, but you can’t assume anything about the type of the objects that you get out. If these restrictions are unacceptable, you can use generic methods (Item 30) or bounded wildcard types (Item 31).
無可否認,這個錯誤消息讓人不滿意,但是編譯器已經完成了它的工作,防止你無視它的元素類型而破壞集合的類型一致性。你不僅不能將任何元素(除 null 之外)放入 `Collection<?>`,而且不能臆想你得到的對象的類型。如果這些限制是不可接受的,你可以使用泛型方法([Item-30](/Chapter-5/Chapter-5-Item-30-Favor-generic-methods.md))或有界通配符類型([Item-31](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.md))。
There are a few minor exceptions to the rule that you should not use raw types. **You must use raw types in class literals.** The specification does not permit the use of parameterized types (though it does permit array types and primitive types) [JLS, 15.8.2]. In other words, List.class, String[].class, and int.class are all legal, but `List<String>.class` and `List<?>.class` are not.
對于不應該使用原始類型的規則,有一些小的例外。**必須在類字面量中使用原始類型。** 該規范不允許使用參數化類型(盡管它允許數組類型和基本類型)[JLS, 15.8.2]。換句話說,`List.class`,`String[].class` 和 `int.class` 都是合法的,但是 `List<String>.class` 和 `List<?>.class` 不是。
A second exception to the rule concerns the instanceof operator. Because generic type information is erased at runtime, it is illegal to use the instanceof operator on parameterized types other than unbounded wildcard types. The use of unbounded wildcard types in place of raw types does not affect the behavior of the instanceof operator in any way. In this case, the angle brackets and question marks are just noise. **This is the preferred way to use the instanceof operator with generic types:**
規則的第二個例外是 instanceof 運算符。由于泛型信息在運行時被刪除,因此在不是無界通配符類型之外的參數化類型上使用 instanceof 操作符是非法的。使用無界通配符類型代替原始類型不會以任何方式影響 instanceof 運算符的行為。在這種情況下,尖括號和問號只是多余的。**下面的例子是使用通用類型 instanceof 運算符的首選方法:**
```
// Legitimate use of raw type - instanceof operator
if (o instanceof Set) { // Raw type
Set<?> s = (Set<?>) o; // Wildcard type
...
}
```
Note that once you’ve determined that o is a Set, you must cast it to the wildcard type `Set<?>`, not the raw type Set. This is a checked cast, so it will not cause a compiler warning.
注意,一旦確定 o 是一個 Set,就必須將其強制轉換為通配符類型 `Set<?>`,而不是原始類型 Set。這是一個經過檢查的強制類型轉換,所以不會引發編譯器警告。
In summary, using raw types can lead to exceptions at runtime, so don’t use them. They are provided only for compatibility and interoperability with legacy code that predates the introduction of generics. As a quick review, `Set<Object>` is a parameterized type representing a set that can contain objects of any type, `Set<?>` is a wildcard type representing a set that can contain only objects of some unknown type, and Set is a raw type, which opts out of the generic type system. The first two are safe, and the last is not.
總之,使用原始類型可能會在運行時導致異常,所以不要輕易使用它們。它們僅用于與引入泛型之前的遺留代碼進行兼容和互操作。快速回顧一下,`Set<Object>` 是一個參數化類型,表示可以包含任何類型的對象的集合,`Set<?>` 是一個通配符類型,表示只能包含某種未知類型的對象的集合,Set 是一個原始類型,它選擇了泛型系統。前兩個是安全的,后一個就不安全了。
For quick reference, the terms introduced in this item (and a few introduced later in this chapter) are summarized in the following table:
為便于參考,本條目中介紹的術語(以及后面將要介紹的一些術語)總結如下:
| Term | Example | Item |
|:-------:|:-------:|:-------:|
| Parameterized type | `List<String>` | [Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md) |
| Actual type parameter | `String` | [Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md) |
| Generic type | `List<E>` | [Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md), [Item-29](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md) |
| Formal type parameter | `E` | [Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md) |
| Unbounded wildcard type | `List<?>` | [Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md) |
| Raw type | `List` | [Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md) |
| Bounded type parameter | `<E extends Number>` | [Item-29](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md) |
| Recursive type bound | `<T extends Comparable<T>>` | [Item-30](/Chapter-5/Chapter-5-Item-30-Favor-generic-methods.md) |
| Bounded wildcard type | `List<? extends Number>` | [Item-31](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.md) |
| Generic method | `static <E> List<E> asList(E[] a)` | [Item-30](/Chapter-5/Chapter-5-Item-30-Favor-generic-methods.md) |
| Type token | `String.class` | [Item-33](/Chapter-5/Chapter-5-Item-33-Consider-typesafe-heterogeneous-containers.md) |
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-5/Chapter-5-Introduction.md)**
- **Next Item(下一條目):[Item 27: Eliminate unchecked warnings(消除 unchecked 警告)](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.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(考慮以序列化代理代替序列化實例)