## Chapter 9. General Programming(通用程序設計)
### Item 61: Prefer primitive types to boxed primitives(基本數據類型優于包裝類)
Java has a two-part type system, consisting of primitives, such as int, double, and boolean, and reference types, such as String and List. Every primitive type has a corresponding reference type, called a boxed primitive. The boxed primitives corresponding to int, double, and boolean are Integer, Double, and Boolean.
Java 有一個由兩部分組成的類型系統,包括基本類型(如 int、double 和 boolean)和引用類型(如 String 和 List)。每個基本類型都有一個對應的引用類型,稱為包裝類型。與 int、double 和 boolean 對應的包裝類是 Integer、Double 和 Boolean。
As mentioned in Item 6, autoboxing and auto-unboxing blur but do not erase the distinction between the primitive and boxed primitive types. There are real differences between the two, and it’s important that you remain aware of which you are using and that you choose carefully between them.
正如 [Item-6](/Chapter-2/Chapter-2-Item-6-Avoid-creating-unnecessary-objects.md) 中提到的,自動裝箱和自動拆箱模糊了基本類型和包裝類型之間的區別,但不會消除它們。這兩者之間有真正的區別,重要的是你要始終意識到正在使用的是哪一種,并在它們之間仔細選擇。
There are three major differences between primitives and boxed primitives. First, primitives have only their values, whereas boxed primitives have identities distinct from their values. In other words, two boxed primitive instances can have the same value and different identities. Second, primitive types have only fully functional values, whereas each boxed primitive type has one nonfunctional value, which is null, in addition to all the functional values of the corresponding primitive type. Last, primitives are more time- and spaceefficient than boxed primitives. All three of these differences can get you into real trouble if you aren’t careful.
基本類型和包裝類型之間有三個主要區別。首先,基本類型只有它們的值,而包裝類型具有與其值不同的標識。換句話說,兩個包裝類型實例可以具有相同的值和不同的標識。第二,基本類型只有全功能值,而每個包裝類型除了對應的基本類型的所有功能值外,還有一個非功能值,即 null。最后,基本類型比包裝類型更節省時間和空間。如果你不小心的話,這三種差異都會給你帶來真正的麻煩。
Consider the following comparator, which is designed to represent ascending numerical order on Integer values. (Recall that a comparator’s compare method returns a number that is negative, zero, or positive, depending on whether its first argument is less than, equal to, or greater than its second.) You wouldn’t need to write this comparator in practice because it implements the natural ordering on Integer, but it makes for an interesting example:
考慮下面的比較器,它的設計目的是表示 Integer 值上的升序數字排序。(回想一下,比較器的 compare 方法返回一個負數、零或正數,這取決于它的第一個參數是小于、等于還是大于第二個參數。)你不需要在實際使用中編寫這個比較器,因為它實現了 Integer 的自然排序,但它提供了一個有趣的例子:
```
// Broken comparator - can you spot the flaw?
Comparator<Integer> naturalOrder =(i, j) -> (i < j) ? -1 : (i == j ? 0 : 1);
```
This comparator looks like it ought to work, and it will pass many tests. For example, it can be used with Collections.sort to correctly sort a millionelement list, whether or not the list contains duplicate elements. But the comparator is deeply flawed. To convince yourself of this, merely print the value of naturalOrder.compare(new Integer(42), new Integer(42)). Both Integer instances represent the same value (42), so the value of this expression should be 0, but it’s 1, which indicates that the first Integer value is greater than the second!
這個比較器看起來應該可以工作,它將通過許多測試。例如,它可以與 `Collections.sort` 一起使用,以正確地排序一個百萬元素的 List,無論該 List 是否包含重復的元素。但這個比較存在嚴重缺陷。要使自己相信這一點,只需打印 `naturalOrder.compare(new Integer(42), new Integer(42))` 的值。兩個 Integer 實例都表示相同的值 `(42)`,所以這個表達式的值應該是 0,但它是 1,這表明第一個 Integer 值大于第二個!
So what’s the problem? The first test in naturalOrder works fine. Evaluating the expression i < j causes the Integer instances referred to by i and j to be auto-unboxed; that is, it extracts their primitive values. The evaluation proceeds to check if the first of the resulting int values is less than the second. But suppose it is not. Then the next test evaluates the expression i==j, which performs an identity comparison on the two object references. If i and j refer to distinct Integer instances that represent the same int value, this comparison will return false, and the comparator will incorrectly return 1, indicating that the first Integer value is greater than the second. **Applying the == operator to boxed primitives is almost always wrong.**
那么問題出在哪里呢?naturalOrder 中的第一個測試工作得很好。計算表達式 `i < j` 會使 i 和 j 引用的 Integer 實例自動拆箱;也就是說,它提取它們的基本類型值。計算的目的是檢查得到的第一個 int 值是否小于第二個 int 值。但假設它不是。然后,下一個測試計算表達式 `i==j`,該表達式對兩個對象引用執行標識比較。如果 i 和 j 引用表示相同 int 值的不同 Integer 實例,這個比較將返回 false,比較器將錯誤地返回 1,表明第一個整型值大于第二個整型值。**將 `==` 操作符應用于包裝類型幾乎都是錯誤的。**
In practice, if you need a comparator to describe a type’s natural order, you should simply call Comparator.naturalOrder(), and if you write a comparator yourself, you should use the comparator construction methods, or the static compare methods on primitive types (Item 14). That said, you could fix the problem in the broken comparator by adding two local variables to store the primitive int values corresponding to the boxed Integer parameters, and performing all of the comparisons on these variables. This avoids the erroneous identity comparison:
在實際使用中,如果你需要一個比較器來描述類型的自然順序,你應該簡單地調用 `Comparator.naturalOrder()`,如果你自己編寫一個比較器,你應該使用比較器構造方法,或者對基本類型使用靜態比較方法([Item-14](/Chapter-3/Chapter-3-Item-14-Consider-implementing-Comparable.md))。也就是說,你可以通過添加兩個局部變量來存儲基本類型 int 值,并對這些變量執行所有的比較,從而修復損壞的比較器中的問題。這避免了錯誤的標識比較:
```
Comparator<Integer> naturalOrder = (iBoxed, jBoxed) -> {
int i = iBoxed, j = jBoxed; // Auto-unboxing
return i < j ? -1 : (i == j ? 0 : 1);
};
```
Next, consider this delightful little program:
接下來,考慮一下這個有趣的小程序:
```
public class Unbelievable {
static Integer i;
public static void main(String[] args) {
if (i == 42)
System.out.println("Unbelievable");
}
}
```
No, it doesn’t print Unbelievable—but what it does is almost as strange. It throws a NullPointerException when evaluating the expression i==42. The problem is that i is an Integer, not an int, and like all nonconstant object reference fields, its initial value is null. When the program evaluates the expression i==42, it is comparing an Integer to an int. In nearly every case **when you mix primitives and boxed primitives in an operation, the boxed primitive is auto-unboxed.** If a null object reference is auto-unboxed, you get a NullPointerException. As this program demonstrates, it can happen almost anywhere. Fixing the problem is as simple as declaring i to be an int instead of an Integer.
不,它不會打印出令人難以置信的東西,但它的行為很奇怪。它在計算表達式 `i==42` 時拋出 NullPointerException。問題是,i 是 Integer,而不是 int 數,而且像所有非常量對象引用字段一樣,它的初值為 null。當程序計算表達式 `i==42` 時,它是在比較 Integer 與 int。**在操作中混合使用基本類型和包裝類型時,包裝類型就會自動拆箱**,這種情況無一例外。如果一個空對象引用自動拆箱,那么你將得到一個 NullPointerException。正如這個程序所演示的,它幾乎可以在任何地方發生。修復這個問題非常簡單,只需將 i 聲明為 int 而不是 Integer。
Finally, consider the program from page 24 in Item 6:
最后,考慮 [Item-6](/Chapter-2/Chapter-2-Item-6-Avoid-creating-unnecessary-objects.md) 中第 24 頁的程序:
```
// Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
```
This program is much slower than it should be because it accidentally declares a local variable (sum) to be of the boxed primitive type Long instead of the primitive type long. The program compiles without error or warning, and the variable is repeatedly boxed and unboxed, causing the observed performance degradation.
這個程序比它預期的速度慢得多,因為它意外地聲明了一個局部變量 `(sum)`,它是包裝類型 Long,而不是基本類型 long。程序在沒有錯誤或警告的情況下編譯,變量被反復裝箱和拆箱,導致產生明顯的性能下降。
In all three of the programs discussed in this item, the problem was the same: the programmer ignored the distinction between primitives and boxed primitives and suffered the consequences. In the first two programs, the consequences were outright failure; in the third, severe performance problems.
在本條目中討論的所有三個程序中,問題都是一樣的:程序員忽略了基本類型和包裝類型之間的區別,并承擔了惡果。在前兩個項目中,結果是徹底的失敗;第三個例子還產生了嚴重的性能問題。
So when should you use boxed primitives? They have several legitimate uses. The first is as elements, keys, and values in collections. You can’t put primitives in collections, so you’re forced to use boxed primitives. This is a special case of a more general one. You must use boxed primitives as type parameters in parameterized types and methods (Chapter 5), because the language does not permit you to use primitives. For example, you cannot declare a variable to be of type `ThreadLocal<int>`, so you must use `ThreadLocal<Integer>` instead. Finally, you must use boxed primitives when making reflective method invocations (Item 65).
那么,什么時候應該使用包裝類型呢?它們有幾個合法的用途。第一個是作為集合中的元素、鍵和值。不能將基本類型放在集合中,因此必須使用包裝類型。這是一般情況下的特例。在參數化類型和方法(Chapter 5)中,必須使用包裝類型作為類型參數,因為 Java 不允許使用基本類型。例如,不能將變量聲明為 `ThreadLocal<int>` 類型,因此必須使用 `ThreadLocal<Integer>`。最后,在進行反射方法調用時,必須使用包裝類型([Item-65](/Chapter-9/Chapter-9-Item-65-Prefer-interfaces-to-reflection.md))。
In summary, use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! **Autoboxing reduces the verbosity, but not the danger, of using boxed primitives.** When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and **when your program does unboxing, it can throw a NullPointerException.** Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
總之,只要有選擇,就應該優先使用基本類型,而不是包裝類型。基本類型更簡單、更快。如果必須使用包裝類型,請小心!**自動裝箱減少了使用包裝類型的冗長,但沒有減少危險。** 當你的程序使用 `==` 操作符比較兩個包裝類型時,它會執行標識比較,這幾乎肯定不是你想要的。當你的程序執行包含包裝類型和基本類型的混合類型計算時,它將進行拆箱,**當你的程序執行拆箱時,將拋出 NullPointerException。** 最后,當你的程序將基本類型裝箱時,可能會導致代價高昂且不必要的對象創建。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-9/Chapter-9-Introduction.md)**
- **Previous Item(上一條目):[Item 60: Avoid float and double if exact answers are required(若需要精確答案就應避免使用 float 和 double 類型)](/Chapter-9/Chapter-9-Item-60-Avoid-float-and-double-if-exact-answers-are-required.md)**
- **Next Item(下一條目):[Item 62: Avoid strings where other types are more appropriate(其他類型更合適時應避免使用字符串)](/Chapter-9/Chapter-9-Item-62-Avoid-strings-where-other-types-are-more-appropriate.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(考慮以序列化代理代替序列化實例)