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 “l(fā)ist of E”), but people often call it List for short. Generic classes and interfaces are collectively known as generic types.
首先,介紹一些術(shù)語派草。聲明中具有一個(gè)或多個(gè)類型參數(shù)的類或接口就是泛型類或泛型接口 [JLS, 8.1.2, 9.1.2]鸽嫂。例如,List 接口有一個(gè)類型參數(shù) E赂乐,用于表示其元素類型。該接口的全名是 List<E>
(讀作「List of E」),但人們通常簡(jiǎn)稱為 List毒租。泛型類和泛型接口統(tǒng)稱為泛型痒谴。
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 “l(fā)ist 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.)
每個(gè)泛型定義了一組參數(shù)化類型衰伯,這些參數(shù)化類型包括類名或接口名,以及帶尖括號(hào)的參數(shù)列表积蔚,參數(shù)列表是與泛型的形式類型參數(shù)相對(duì)應(yīng)的實(shí)際類型 [JLS, 4.4, 4.5]意鲸。例如,List<String>
(讀作「List of String」)是一個(gè)參數(shù)化類型尽爆,表示元素類型為 String 類型的 List怎顾。(String 是與形式類型參數(shù) E 對(duì)應(yīng)的實(shí)際類型參數(shù)。)
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.
最后漱贱,每個(gè)泛型都定義了一個(gè)原始類型槐雾,它是沒有任何相關(guān)類型參數(shù)的泛型的名稱 [JLS, 4.8]。例如幅狮,List<E>
對(duì)應(yīng)的原始類型是 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 之前擎值,這是一個(gè)典型的集合聲明。就 Java 9 而言逐抑,它仍然是合法的鸠儿,但不應(yīng)效仿:
// 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):
如果你今天使用這個(gè)聲明,然后意外地將 coin 放入 stamp 集合中泵肄,這一錯(cuò)誤的插入依然能夠編譯并沒有錯(cuò)誤地運(yùn)行(盡管編譯器確實(shí)發(fā)出了模糊的警告):
// 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 時(shí)才會(huì)收到錯(cuò)誤提示:
// 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.”
正如在本書中提到的捆交,在出現(xiàn)錯(cuò)誤之后盡快發(fā)現(xiàn)錯(cuò)誤是有價(jià)值的淑翼,最好是在編譯時(shí)。在本例這種情況下品追,直到運(yùn)行時(shí)(在錯(cuò)誤發(fā)生很久之后)才發(fā)現(xiàn)錯(cuò)誤玄括,而且報(bào)錯(cuò)代碼可能與包含錯(cuò)誤的代碼相距很遠(yuǎn)。一旦看到 ClassCastException肉瓦,就必須在代碼中搜索將 coin 放進(jìn) stamp 集合的方法調(diào)用遭京。編譯器不能幫助你,因?yàn)樗荒芾斫庾⑨尅窩ontains only Stamp instances.」
With generics, the type declaration contains the information, not the comment:
對(duì)于泛型泞莉,類型聲明應(yīng)該包含類型信息哪雕,而不是注釋:
// 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:
從這個(gè)聲明看出,編譯器應(yīng)該知道 stamps 應(yīng)該只包含 Stamp 實(shí)例鲫趁,為保證它確實(shí)如此斯嚎,假設(shè)你的整個(gè)代碼庫編譯沒有發(fā)出(或抑制;詳見 Item-27)任何警告挨厚。當(dāng) stamps 利用一個(gè)參數(shù)化的類型進(jìn)行聲明時(shí)堡僻,錯(cuò)誤的插入將生成編譯時(shí)錯(cuò)誤消息,該消息將確切地告訴你哪里出了問題:
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(v. [計(jì)] 檢索疫剃;恢復(fù)钉疫;取回;補(bǔ)償) 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.
當(dāng)從集合中檢索元素時(shí)巢价,編譯器會(huì)為你執(zhí)行不可見的強(qiáng)制類型轉(zhuǎn)換牲阁,并確保它們不會(huì)失敗(再次假設(shè)你的所有代碼沒有產(chǎn)生或抑制任何編譯器警告)壤躲。雖然不小心將 coin 插入 stamps 集合看起來有些牽強(qiáng)城菊,但這類問題是真實(shí)存在的。例如柒爵,很容易想象將一個(gè) BigInteger 放入一個(gè)只包含 BigDecimal 實(shí)例的集合中役电。
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).
如前所述赚爵,使用原始類型(沒有類型參數(shù)的泛型)是合法的棉胀,但是你永遠(yuǎn)不應(yīng)該這樣做。如果使用原始類型冀膝,就會(huì)失去泛型的安全性和表現(xiàn)力。 既然你不應(yīng)該使用它們,那么為什么語言設(shè)計(jì)者一開始就允許原始類型呢悄但?答案是:為了兼容性梭域。Java 即將進(jìn)入第二個(gè)十年,泛型被添加進(jìn)來時(shí)赐纱,還存在大量不使用泛型的代碼脊奋。保持所有這些代碼合法并與使用泛型的新代碼兼容被認(rèn)為是關(guān)鍵的熬北。將參數(shù)化類型的實(shí)例傳遞給設(shè)計(jì)用于原始類型的方法必須是合法的,反之亦然诚隙。這被稱為遷移兼容性的需求讶隐,它促使原始類型得到支持并使用擦除實(shí)現(xiàn)泛型 (Item-28)。
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<Object>.
雖然你不應(yīng)該使用原始類型(如 List)久又,但是可以使用參數(shù)化的類型來允許插入任意對(duì)象巫延,如 List<Object>
。原始類型 List 和參數(shù)化類型 List<Object>
之間的區(qū)別是什么地消?粗略地說炉峰,前者選擇了不使用泛型系統(tǒng),而后者明確地告訴編譯器它能夠保存任何類型的對(duì)象脉执。雖然可以將 List<String>
傳遞給 List 類型的參數(shù)疼阔,但不能將其傳遞給類型 List<Object>
的參數(shù)。泛型有子類型規(guī)則半夷,List<String>
是原始類型 List 的子類型竿开,而不是參數(shù)化類型 List<Object>
的子類型(Item-28)。因此玻熙,如果使用原始類型(如 List)否彩,就會(huì)失去類型安全性,但如果使用參數(shù)化類型(如 List<Object>
)則不會(huì)嗦随。
To make this concrete, consider the following program:
為了使這一點(diǎn)具體些列荔,考慮下面的程序:
// 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:
該程序可以編譯,但因?yàn)樗褂迷碱愋?List枚尼,所以你會(huì)得到一個(gè)警告:
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.
實(shí)際上贴浙,如果你運(yùn)行程序,當(dāng)程序試圖將調(diào)用 strings.get(0) 的結(jié)果強(qiáng)制轉(zhuǎn)換為字符串時(shí)署恍,你會(huì)得到一個(gè) ClassCastException崎溃。這是一個(gè)由編譯器生成的強(qiáng)制類型轉(zhuǎn)換,它通常都能成功盯质,但在本例中袁串,我們忽略了編譯器的警告,并為此付出了代價(jià)呼巷。
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 替換為參數(shù)化類型 List<Object>
囱修,并嘗試重新編譯程序,你會(huì)發(fā)現(xiàn)它不再編譯王悍,而是發(fā)出錯(cuò)誤消息:
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:
對(duì)于元素類型未知且無關(guān)緊要的集合破镰,你可能會(huì)嘗試使用原始類型。例如,假設(shè)你希望編寫一個(gè)方法鲜漩,該方法接受兩個(gè)集合并返回它們共有的元素?cái)?shù)量源譬。如果你是使用泛型的新手,那么你可以這樣編寫一個(gè)方法:
// 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:
這種方法是可行的孕似,但是它使用的是原始類型瓶佳,這是很危險(xiǎn)的。安全的替代方法是使用無界通配符類型鳞青。如果你想使用泛型霸饲,但不知道或不關(guān)心實(shí)際的類型參數(shù)是什么,那么可以使用問號(hào)代替臂拓。例如厚脉,泛型集 Set<E>
的無界通配符類型是 Set<?>
(讀作「set of some type」)。它是最通用的參數(shù)化集合類型胶惰,能夠容納任何集合:
// 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 之間的區(qū)別是什么傻工?問號(hào)真的能起作用嗎?我并不是在強(qiáng)調(diào)這一點(diǎn)孵滞,但是通配符類型是安全的中捆,而原始類型則不是。將任何元素放入具有原始類型的集合中坊饶,很容易破壞集合的類型一致性(如上述的 unsafeAdd 方法所示)泄伪;你不能將任何元素(除了 null)放入 Collection<?>
。嘗試這樣做將生成這樣的編譯時(shí)錯(cuò)誤消息:
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(vt. 使腐爛匿级;使墮落蟋滴,使惡化) the collection’s type invariant(n. [數(shù)] 不變量;[計(jì)] 不變式), 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).
無可否認(rèn)痘绎,這個(gè)錯(cuò)誤消息讓人不滿意津函,但是編譯器已經(jīng)完成了它的工作,防止你無視它的元素類型而破壞集合的類型一致性孤页。你不僅不能將任何元素(除 null 之外)放入 Collection<?>
尔苦,而且不能臆想你得到的對(duì)象的類型。如果這些限制是不可接受的行施,你可以使用泛型方法(Item-30)或有界通配符類型(Item-31)允坚。
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.
對(duì)于不應(yīng)該使用原始類型的規(guī)則,有一些小的例外悲龟。必須在類字面量中使用原始類型屋讶。 該規(guī)范不允許使用參數(shù)化類型(盡管它允許數(shù)組類型和基本類型)[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:
規(guī)則的第二個(gè)例外是 instanceof 運(yùn)算符乐疆。由于泛型信息在運(yùn)行時(shí)被刪除,因此在不是無界通配符類型之外的參數(shù)化類型上使用 instanceof 操作符是非法的贬养。使用無界通配符類型代替原始類型不會(huì)以任何方式影響 instanceof 運(yùn)算符的行為挤土。在這種情況下,尖括號(hào)和問號(hào)只是多余的误算。下面的例子是使用通用類型 instanceof 運(yùn)算符的首選方法:
// 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 是一個(gè) Set,就必須將其強(qiáng)制轉(zhuǎn)換為通配符類型 Set<?>
儿礼,而不是原始類型 Set咖杂。這是一個(gè)經(jīng)過檢查的強(qiáng)制類型轉(zhuǎn)換,所以不會(huì)引發(fā)編譯器警告蚊夫。
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(n. 通配符) type representing(v. 代表诉字;表示,表現(xiàn)) 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.
總之知纷,使用原始類型可能會(huì)在運(yùn)行時(shí)導(dǎo)致異常壤圃,所以不要輕易使用它們。它們僅用于與引入泛型之前的遺留代碼進(jìn)行兼容和互操作琅轧∥樯快速回顧一下,Set<Object>
是一個(gè)參數(shù)化類型乍桂,表示可以包含任何類型的對(duì)象的集合墨叛,Set<?>
是一個(gè)通配符類型,表示只能包含某種未知類型的對(duì)象的集合模蜡,Set 是一個(gè)原始類型漠趁,它選擇了泛型系統(tǒng)。前兩個(gè)是安全的忍疾,后一個(gè)就不安全了闯传。
For quick reference, the terms introduced in this item (and a few introduced later in this chapter) are summarized in the following table:
為便于參考,本條目中介紹的術(shù)語(以及后面將要介紹的一些術(shù)語)總結(jié)如下:
Term | Example | Item |
---|---|---|
Parameterized type | List<String> |
Item-26 |
Actual type parameter | String |
Item-26 |
Generic type | List<E> |
Item-26, Item-29 |
Formal type parameter | E |
Item-26 |
Unbounded wildcard type | List<?> |
Item-26 |
Raw type | List |
Item-26 |
Bounded type parameter | <E extends Number> |
Item-29 |
Recursive type bound | <T extends Comparable<T>> |
Item-30 |
Bounded wildcard type | List<? extends Number> |
Item-31 |
Generic method | static <E> List<E> asList(E[] a) |
Item-30 |
Type token | String.class |
Item-33 |
Back to contents of the chapter(返回章節(jié)目錄)
- Next Item(下一條目):Item 27: Eliminate unchecked warnings(消除 unchecked 警告)