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

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                ## 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&lt;Object&gt;.** 雖然你不應該使用原始類型(如 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)**
                  <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>

                              哎呀哎呀视频在线观看