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

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                ## 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)**
                  <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>

                              哎呀哎呀视频在线观看