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

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ## Chapter 8. Methods(方法) ### Item 53: Use varargs judiciously(明智地使用可變參數) Varargs methods, formally known as variable arity methods [JLS, 8.4.1], accept zero or more arguments of a specified type. The varargs facility works by first creating an array whose size is the number of arguments passed at the call site, then putting the argument values into the array, and finally passing the array to the method. 可變參數方法的正式名稱是 variable arity methods [JLS, 8.4.1],它接受指定類型的零個或多個參數。可變參數首先創建一個數組,其大小是在調用點上傳遞的參數數量,然后將參數值放入數組,最后將數組傳遞給方法。 For example, here is a varargs method that takes a sequence of int arguments and returns their sum. As you would expect, the value of sum(1, 2, 3) is 6, and the value of sum() is 0: 例如,這里有一個可變參數方法,它接受一系列 int 參數并返回它們的和。如你所料,`sum(1, 2, 3)` 的值為 6,`sum()` 的值為 0: ``` // Simple use of varargs static int sum(int... args) { int sum = 0; for (int arg : args) sum += arg; return sum; } ``` Sometimes it’s appropriate to write a method that requires one or more arguments of some type, rather than zero or more. For example, suppose you want to write a function that computes the minimum of its arguments. This function is not well defined if the client passes no arguments. You could check the array length at runtime: 有時,編寫一個方法需要一個或多個某種類型的參數,而不是零個或多個參數,這是合適的。例如,假設你想編寫一個函數來計算其參數的最小值。如果客戶端不傳遞參數,則此函數定義得不好。你可以在運行時檢查數組長度: ``` // The WRONG way to use varargs to pass one or more arguments! static int min(int... args) { if (args.length == 0) throw new IllegalArgumentException("Too few arguments"); int min = args[0]; for (int i = 1; i < args.length; i++) if (args[i] < min) min = args[i]; return min; } ``` This solution has several problems. The most serious is that if the client invokes this method with no arguments, it fails at runtime rather than compile time. Another problem is that it is ugly. You have to include an explicit validity check on args, and you can’t use a for-each loop unless you initialize min to Integer.MAX_VALUE, which is also ugly. 這個解決方案有幾個問題。最嚴重的情況是,如果客戶端不帶參數調用此方法,那么它將在運行時而不是編譯時失敗。另一個問題是它不美觀。必須包含對 args 的顯式有效性檢查,并且不能使用 for-each 循環,除非將 min 初始化為 Integer.MAX_VALUE,也很不美觀。 Luckily there’s a much better way to achieve the desired effect. Declare the method to take two parameters, one normal parameter of the specified type and one varargs parameter of this type. This solution corrects all the deficiencies of the previous one: 幸運的是,有一種更好的方法可以達到預期的效果。聲明方法獲取兩個參數,一個指定類型的常規參數和一個該類型的可變參數。這個解決方案彌補了前一個解決方案的所有不足: ``` // The right way to use varargs to pass one or more arguments static int min(int firstArg, int... remainingArgs) { int min = firstArg; for (int arg : remainingArgs) if (arg < min) min = arg; return min; } ``` As you can see from this example, varargs are effective in circumstances where you want a method with a variable number of arguments. Varargs were designed for printf, which was added to the platform at the same time as varargs, and for the core reflection facility (Item 65), which was retrofitted. Both printf and reflection benefited enormously from varargs. 從這個例子中可以看出,在方法需要參數數量可變的情況下,可變參數是有效的。可變參數是為 printf 和經過改造的核心反射機制([Item-65](/Chapter-9/Chapter-9-Item-65-Prefer-interfaces-to-reflection.md))而設計的,它們與可變參數同時被添加到 JDK,printf 和 reflection 都從可變參數中受益匪淺。 Exercise care when using varargs in performance-critical situations. Every invocation of a varargs method causes an array allocation and initialization. If you have determined empirically that you can’t afford this cost but you need the flexibility of varargs, there is a pattern that lets you have your cake and eat it too. Suppose you’ve determined that 95 percent of the calls to a method have three or fewer parameters. Then declare five overloadings of the method, one each with zero through three ordinary parameters, and a single varargs method for use when the number of arguments exceeds three: 在性能關鍵的情況下使用可變參數時要小心。每次調用可變參數方法都會導致數組分配和初始化。如果你已經從經驗上確定你負擔不起這個成本,但是你仍需要可變參數的靈活性,那么有一種模式可以讓你魚與熊掌兼得。假設你已經確定對方法 95% 的調用只需要三個或更少的參數。可以聲明該方法的 5 個重載,每個重載 0 到 3 個普通參數,當參數數量超過 3 個時引入可變參數: ``` public void foo() { } public void foo(int a1) { } public void foo(int a1, int a2) { } public void foo(int a1, int a2, int a3) { } public void foo(int a1, int a2, int a3, int... rest) { } ``` Now you know that you’ll pay the cost of the array creation only in the 5 percent of all invocations where the number of parameters exceeds three. Like most performance optimizations, this technique usually isn’t appropriate, but when it is, it’s a lifesaver. 現在你知道,在所有參數數量超過 3 的調用中,只有 5% 的調用需要付出創建數組的成本。與大多數性能優化一樣,這種技術使用并不廣泛,但當它合適出現時,就是一個救星。 The static factories for EnumSet use this technique to reduce the cost of creating enum sets to a minimum. This was appropriate because it was critical that enum sets provide a performance-competitive replacement for bit fields (Item 36). EnumSet 的靜態工廠使用這種技術將創建枚舉集的成本降到最低。這是適當的,因為 enum 集合為位字段提供具有性能競爭力的替代方法是至關重要的([Item-36](/Chapter-6/Chapter-6-Item-36-Use-EnumSet-instead-of-bit-fields.md))。 In summary, varargs are invaluable when you need to define methods with a variable number of arguments. Precede the varargs parameter with any required parameters, and be aware of the performance consequences of using varargs. 總之,當你需要定義具有不確定數量參數的方法時,可變參數是非常有用的。在可變參數之前加上任何必需的參數,并注意使用可變參數可能會引發的性能后果。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-8/Chapter-8-Introduction.md)** - **Previous Item(上一條目):[Item 52: Use overloading judiciously(明智地使用重載)](/Chapter-8/Chapter-8-Item-52-Use-overloading-judiciously.md)** - **Next Item(下一條目):[Item 54: Return empty collections or arrays not nulls](/Chapter-8/Chapter-8-Item-54-Return-empty-collections-or-arrays-not-nulls.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>

                              哎呀哎呀视频在线观看