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

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                ## Chapter 5. Generics(泛型) ### Item 28: Prefer lists to arrays(list 優于數組) Arrays differ from generic types in two important ways. First, arrays are covariant. This scary-sounding word means simply that if Sub is a subtype of Super, then the array type Sub[] is a subtype of the array type Super[]. Generics, by contrast, are invariant: for any two distinct types Type1 and Type2, `List<Type1>` is neither a subtype nor a supertype of `List<Type2>` [JLS, 4.10; Naftalin07, 2.5]. You might think this means that generics are deficient, but arguably(可能,大概) it is arrays that are deficient. This code fragment is legal: 數組與泛型有兩個重要區別。首先,數組是協變的。這個聽起來很嚇人的單詞的意思很簡單,如果 Sub 是 Super 的一個子類型,那么數組類型 Sub[] 就是數組類型 Super[] 的一個子類型。相比之下,泛型是不變的:對于任何兩個不同類型 Type1 和 Type2,`List<Type1>` 既不是 `List<Type2>` 的子類型,也不是 `List<Type2>` 的超類型 [JLS, 4.10; Naftalin07, 2.5]。你可能認為這意味著泛型是有缺陷的,但可以說數組才是有缺陷的。這段代碼是合法的: ``` // Fails at runtime! Object[] objectArray = new Long[1]; objectArray[0] = "I don't fit in"; // Throws ArrayStoreException ``` but this one is not: 但這一段代碼就不是: ``` // Won't compile! List<Object> ol = new ArrayList<Long>(); // Incompatible types ol.add("I don't fit in"); ``` Either way you can’t put a String into a Long container, but with an array you find out that you’ve made a mistake at runtime; with a list, you find out at compile time. Of course, you’d rather find out at compile time. 兩種方法都不能將 String 放入 Long 容器,但使用數組,你會得到一個運行時錯誤;使用 list,你可以在編譯時發現問題。當然,你更希望在編譯時找到問題。 The second major difference between arrays and generics is that arrays are reified [JLS, 4.7]. This means that arrays know and enforce their element type at runtime. As noted earlier, if you try to put a String into an array of Long, you’ll get an ArrayStoreException. Generics, by contrast, are implemented by erasure [JLS, 4.6]. This means that they enforce their type constraints only at compile time and discard (or erase) their element type information at runtime. Erasure is what allowed generic types to interoperate freely with legacy code that didn’t use generics (Item 26), ensuring a smooth transition to generics in Java 5. 數組和泛型之間的第二個主要區別:數組是具體化的 [JLS, 4.7]。這意味著數組在運行時知道并強制執行他們的元素類型。如前所述,如果試圖將 String 元素放入一個 Long 類型的數組中,就會得到 ArrayStoreException。相比之下,泛型是通過擦除來實現的 [JLS, 4.6]。這意味著它們只在編譯時執行類型約束,并在運行時丟棄(或擦除)元素類型信息。擦除允許泛型與不使用泛型的遺留代碼自由交互操作([Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md)),確保在 Java 5 中平穩地過渡。 Because of these fundamental differences, arrays and generics do not mix well. For example, it is illegal to create an array of a generic type, a parameterized type, or a type parameter. Therefore, none of these array creation expressions are legal: `new List<E>[]`, `new List<String>[]`, `new E[]`. All will result in generic array creation errors at compile time. 由于這些基本差異,數組和泛型不能很好地混合。例如,創建泛型、參數化類型或類型參數的數組是非法的。因此,這些數組創建表達式都不是合法的:`new List<E>[]`、`new List<String>[]`、`new E[]`。所有這些都會在編譯時導致泛型數組創建錯誤。 Why is it illegal to create a generic array? Because it isn’t typesafe. If it were legal, casts generated by the compiler in an otherwise correct program could fail at runtime with a ClassCastException. This would violate the fundamental guarantee provided by the generic type system. 為什么創建泛型數組是非法的?因為這不是類型安全的。如果合法,編譯器在其他正確的程序中生成的強制轉換在運行時可能會失敗,并導致 ClassCastException。這將違反泛型系統提供的基本保證。 To make this more concrete, consider the following code fragment: 為了更具體,請考慮以下代碼片段: ``` // Why generic array creation is illegal - won't compile! List<String>[] stringLists = new List<String>[1]; // (1) List<Integer> intList = List.of(42); // (2) Object[] objects = stringLists; // (3) objects[0] = intList; // (4) String s = stringLists[0].get(0); // (5) ``` Let’s pretend that line 1, which creates a generic array, is legal. Line 2 creates and initializes a `List<Integer>` containing a single element. Line 3 stores the `List<String>` array into an Object array variable, which is legal because arrays are covariant. Line 4 stores the `List<Integer>` into the sole element of the Object array, which succeeds because generics are implemented by erasure: the runtime type of a `List<Integer>` instance is simply List, and the runtime type of a `List<String>`[] instance is List[], so this assignment doesn’t generate an ArrayStoreException. Now we’re in trouble. We’ve stored a `List<Integer>` instance into an array that is declared to hold only `List<String>` instances. In line 5, we retrieve the sole element from the sole list in this array. The compiler automatically casts the retrieved element to String, but it’s an Integer, so we get a ClassCastException at runtime. In order to prevent this from happening, line 1 (which creates a generic array) must generate a compile-time error. 假設創建泛型數組的第 1 行是合法的。第 2 行創建并初始化一個包含單個元素的 `List<Integer>`。第 3 行將 `List<String>` 數組存儲到 Object 類型的數組變量中,這是合法的,因為數組是協變的。第 4 行將 `List<Integer>` 存儲到 Object 類型的數組的唯一元素中,這是成功的,因為泛型是由擦除實現的:`List<Integer>` 實例的運行時類型是 List,`List<String>`[] 實例的運行時類型是 List[],因此這個賦值不會生成 ArrayStoreException。現在我們有麻煩了。我們將一個 `List<Integer>` 實例存儲到一個數組中,該數組聲明只保存 `List<String>` 實例。在第 5 行,我們從這個數組的唯一列表中檢索唯一元素。編譯器自動將檢索到的元素轉換為 String 類型,但它是一個 Integer 類型的元素,因此我們在運行時得到一個 ClassCastException。為了防止這種情況發生,第 1 行(創建泛型數組)必須生成編譯時錯誤。 Types such as E, `List<E>`, and `List<String>` are technically known as nonreifiable types [JLS, 4.7]. Intuitively speaking, a non-reifiable type is one whose runtime representation contains less information than its compile-time representation. Because of erasure, the only parameterized types that are reifiable are unbounded wildcard types such as `List<?>` and `Map<?,?>` (Item 26). It is legal, though rarely useful, to create arrays of unbounded wildcard types. E、`List<E>` 和 `List<string>` 等類型在技術上稱為不可具體化類型 [JLS, 4.7]。直觀地說,非具體化類型的運行時表示包含的信息少于其編譯時表示。由于擦除,唯一可具體化的參數化類型是無限制通配符類型,如 `List<?>` 和 `Map<?,?>`([Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md))。創建無邊界通配符類型數組是合法的,但不怎么有用。 The prohibition on generic array creation can be annoying. It means, for example, that it’s not generally possible for a generic collection to return an array of its element type (but see Item 33 for a partial solution). It also means that you get confusing warnings when using varargs methods (Item 53) in combination with generic types. This is because every time you invoke a varargs method, an array is created to hold the varargs parameters. If the element type of this array is not reifiable, you get a warning. The SafeVarargs annotation can be used to address this issue (Item 32). 禁止創建泛型數組可能很煩人。例如,這意味著泛型集合通常不可能返回其元素類型的數組(部分解決方案請參見 [Item-33](/Chapter-5/Chapter-5-Item-33-Consider-typesafe-heterogeneous-containers.md))。這也意味著在使用 varargs 方法([Item-53](/Chapter-8/Chapter-8-Item-53-Use-varargs-judiciously.md))與泛型組合時,你會得到令人困惑的警告。這是因為每次調用 varargs 方法時,都會創建一個數組來保存 varargs 參數。如果該數組的元素類型不可具體化,則會得到警告。SafeVarargs 注解可以用來解決這個問題([Item-32](/Chapter-5/Chapter-5-Item-32-Combine-generics-and-varargs-judiciously.md))。 **譯注:varargs 方法,指帶有可變參數的方法。** When you get a generic array creation error or an unchecked cast warning on a cast to an array type, the best solution is often to use the collection type `List<E>` in preference to the array type E[]. You might sacrifice some conciseness or performance, but in exchange you get better type safety and interoperability. 當你在轉換為數組類型時遇到泛型數組創建錯誤或 unchecked 強制轉換警告時,通常最好的解決方案是使用集合類型 `List<E>`,而不是數組類型 E[]。你可能會犧牲一些簡潔性或性能,但作為交換,你可以獲得更好的類型安全性和互操作性。 For example, suppose you want to write a Chooser class with a constructor that takes a collection, and a single method that returns an element of the collection chosen at random. Depending on what collection you pass to the constructor, you could use a chooser as a game die, a magic 8-ball, or a data source for a Monte Carlo simulation. Here’s a simplistic implementation without generics: 例如,假設你希望編寫一個 Chooser 類,該類的構造函數接受一個集合,而單個方法返回隨機選擇的集合元素。根據傳遞給構造函數的集合,可以將選擇器用作游戲骰子、魔術 8 球或蒙特卡洛模擬的數據源。下面是一個沒有泛型的簡單實現: ``` // Chooser - a class badly in need of generics! public class Chooser { private final Object[] choiceArray; public Chooser(Collection choices) { choiceArray = choices.toArray(); } public Object choose() { Random rnd = ThreadLocalRandom.current(); return choiceArray[rnd.nextInt(choiceArray.length)]; } } ``` To use this class, you have to cast the choose method’s return value from Object to the desired type every time you use invoke the method, and the cast will fail at runtime if you get the type wrong. Taking the advice of Item 29 to heart, we attempt to modify Chooser to make it generic. Changes are shown in boldface: 要使用這個類,每次使用方法調用時,必須將 choose 方法的返回值從對象轉換為所需的類型,如果類型錯誤,轉換將在運行時失敗。我們認真考慮了 [Item-29](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md) 的建議,試圖對 Chooser 進行修改,使其具有通用性。變化以粗體顯示: ``` // A first cut at making Chooser generic - won't compile public class Chooser<T> { private final T[] choiceArray; public Chooser(Collection<T> choices) { choiceArray = choices.toArray(); } // choose method unchanged } ``` If you try to compile this class, you’ll get this error message: 如果你嘗試編譯這個類,你將得到這樣的錯誤消息: ``` Chooser.java:9: error: incompatible types: Object[] cannot be converted to T[] choiceArray = choices.toArray(); ^ where T is a type-variable: T extends Object declared in class Chooser ``` No big deal, you say, I’ll cast the Object array to a T array: 沒什么大不了的,你會說,我把對象數組轉換成 T 數組: ``` choiceArray = (T[]) choices.toArray(); ``` This gets rid of the error, but instead you get a warning: 這樣就消除了錯誤,但你得到一個警告: ``` Chooser.java:9: warning: [unchecked] unchecked cast choiceArray = (T[]) choices.toArray(); ^ required: T[], found: Object[] where T is a type-variable: T extends Object declared in class Chooser ``` The compiler is telling you that it can’t vouch for the safety of the cast at runtime because the program won’t know what type T represents—remember, element type information is erased from generics at runtime. Will the program work? Yes, but the compiler can’t prove it. You could prove it to yourself, put the proof in a comment and suppress the warning with an annotation, but you’re better off eliminating the cause of warning (Item 27). 編譯器告訴你,它不能保證在運行時轉換的安全性,因為程序不知道類型 T 代表什么。記住,元素類型信息在運行時從泛型中刪除。這個計劃會奏效嗎?是的,但是編譯器不能證明它。你可以向自己證明這一點,但是你最好將證據放在注釋中,指出消除警告的原因([Item-27](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md)),并使用注解隱藏警告。 To eliminate the unchecked cast warning, use a list instead of an array. Here is a version of the Chooser class that compiles without error or warning: 若要消除 unchecked 強制轉換警告,請使用 list 而不是數組。下面是編譯時沒有錯誤或警告的 Chooser 類的一個版本: ``` // List-based Chooser - typesafe public class Chooser<T> { private final List<T> choiceList; public Chooser(Collection<T> choices) { choiceList = new ArrayList<>(choices); } public T choose() { Random rnd = ThreadLocalRandom.current(); return choiceList.get(rnd.nextInt(choiceList.size())); } } ``` This version is a tad more verbose, and perhaps a tad slower, but it’s worth it for the peace of mind that you won’t get a ClassCastException at runtime. 這個版本稍微有點冗長,可能稍微慢一些,但是為了讓你安心,在運行時不會得到 ClassCastException 是值得的。 In summary, arrays and generics have very different type rules. Arrays are covariant and reified; generics are invariant and erased. As a consequence, arrays provide runtime type safety but not compile-time type safety, and vice versa for generics. As a rule, arrays and generics don’t mix well. If you find yourself mixing them and getting compile-time errors or warnings, your first impulse should be to replace the arrays with lists. 總之,數組和泛型有非常不同的類型規則。數組是協變的、具體化的;泛型是不變的和可被擦除的。因此,數組提供了運行時類型安全,而不是編譯時類型安全,對于泛型反之亦然。一般來說,數組和泛型不能很好地混合。如果你發現將它們混合在一起并得到編譯時錯誤或警告,那么你的第一個反應該是將數組替換為 list。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-5/Chapter-5-Introduction.md)** - **Previous Item(上一條目):[Item 27: Eliminate unchecked warnings(消除 unchecked 警告)](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md)** - **Next Item(下一條目):[Item 29: Favor generic types(優先使用泛型)](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.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>

                              哎呀哎呀视频在线观看