泛型型協變逆變
by Fabian Terh
由Fabian Terh
Java泛型類型簡介:協變和逆變 (An introduction to generic types in Java: covariance and contravariance)
種類 (Types)
Java is a statically typed language, which means you must first declare a variable and its type before using it.
Java是一種靜態類型的語言,這意味著您必須先聲明一個變量及其類型,然后才能使用它。
For example: int myInteger = 42;
例如: int myInteger = 42;
Enter generic types.
輸入通用類型。
通用類型 (Generic types)
Definition: “A generic type is a generic class or interface that is parameterized over types.”
定義 :“ 泛型類型是通過類型進行參數化的泛型類或接口。”
Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.
本質上,泛型類型允許您編寫可與不同類型一起使用的泛型通用類(或方法),從而可以重復使用代碼。
Rather than specifying obj
to be of an int
type, or a String
type, or any other type, you define the Box
class to accept a type parameter <
;T>. Then, you can
use T to represent that generic type in any part within your class.
您可以將Box
類定義為接受類型參數<
; T>,而不是將obj
指定為int
類型, String
類型或任何其他類型。 然后,CA n
用t代表在類中的任何一部分泛型類型。
Now, enter covariance and contravariance.
現在,輸入協方差和自變量。
協方差和自變量 (Covariance and contravariance)
定義 (Definition)
Variance refers to how subtyping between more complex types relates to subtyping between their components (source).
差異是指更復雜類型之間的子類型如何與其組件( 源 )之間的子類型相關。
An easy-to-remember (and extremely informal) definition of covariance and contravariance is:
協方差和協方差的一個易于記憶(非常非正式)的定義是:
- Covariance: accept subtypes 協方差:接受子類型
- Contravariance: accept supertypes 矛盾:接受超類型
數組 (Arrays)
In Java, arrays are covariant, which has 2 implications.
在Java中, 數組是covariant ,有2個含義。
Firstly, an array of type T[]
may contain elements of type T
and its subtypes.
首先,類型為T[]
的數組可以包含類型T
及其子類型的元素。
Number[] nums = new Number[5];nums[0] = new Integer(1); // Oknums[1] = new Double(2.0); // Ok
Secondly, an array of type S[]
is a subtype of T[]
if S
is a subtype of T
.
其次,類型的數組S[]
是的子類型T[]
如果S
是的子類型T
。
Integer[] intArr = new Integer[5];Number[] numArr = intArr; // Ok
However, it’s important to remember that: (1) numArr
is a reference of reference type Number[]
to the “actual object” intArr
of “actual type” Integer[]
.
但是,重要的是要記住:(1) numArr
是引用類型Number[]
對“ actual type” Integer[]
的“ actual object” intArr
。
Therefore, the following line will compile just fine, but will produce a runtime ArrayStoreException
(because of heap pollution):
因此,以下行將編譯得很好,但將生成運行時ArrayStoreException
(由于堆污染):
numArr[0] = 1.23; // Not ok
It produces a runtime exception, because Java knows at runtime that the “actual object” intArr
is actually an array of Integer
.
它產生一個運行時異常,因為Java在運行時知道“實際對象” intArr
實際上是Integer
的數組。
泛型 (Generics)
With generic types, Java has no way of knowing at runtime the type information of the type parameters, due to type erasure. Therefore, it cannot protect against heap pollution at runtime.
對于泛型類型,由于類型擦除,Java無法在運行時知道類型參數的類型信息。 因此,它無法在運行時防止堆污染。
As such, generics are invariant.
因此,泛型是不變的。
ArrayList<Integer> intArrList = new ArrayList<>();ArrayList<Number> numArrList = intArrList; // Not okArrayList<Integer> anotherIntArrList = intArrList; // Ok
The type parameters must match exactly, to protect against heap pollution.
類型參數必須完全匹配,以防止堆污染。
But enter wildcards.
但是輸入通配符。
通配符,協方差和逆方差 (Wildcards, covariance, and contravariance)
With wildcards, it’s possible for generics to support covariance and contravariance.
使用通配符,泛型有可能支持協方差和協方差。
Tweaking the previous example, we get this, which works!
調整前面的示例,我們得到了這個,它有效!
ArrayList<Integer> intArrList = new ArrayList<>();ArrayList<? super Integer> numArrList = intArrList; // Ok
The question mark “?” refers to a wildcard which represents an unknown type. It can be lower-bounded, which restricts the unknown type to be a specific type or its supertype.
問號“?” 表示代表未知類型的通配符。 它可以是下界的,這將未知類型限制為特定類型或其超類型。
Therefore, in line 2, ? super Integer
translates to “any type that is an Integer type or its supertype”.
因此,在第2行, ? super Integer
? super Integer
轉換為“任何為Integer類型或其超類型的類型”。
You could also upper-bound the wildcard, which restricts the unknown type to be a specific type or its subtype, by using ? extends Integer
.
您還可以使用? extends Integer
來限制通配符的范圍,通配符將未知類型限制為特定類型或其子類型? extends Integer
? extends Integer
。
只讀和只寫 (Read-only and write-only)
Covariance and contravariance produce some interesting outcomes. Covariant types are read-only, while contravariant types are write-only.
協方差和自變量產生一些有趣的結果。 協變類型是只讀的,而協變類型是只寫的。
Remember that covariant types accept subtypes, so ArrayList<? extends Numb
er> can contain any object that is either of a
Number type or its subtype.
還記得協變類型接受子類型ArrayList<? extends Numb
,所以ArrayList<? extends Numb
ArrayList<? extends Numb
ER>可以包含任何對象,或者是of a
數字類型或子類型。
In this example, line 9 works, because we can be certain that whatever we get from the ArrayList can be upcasted to a Number
type (because if it extends Number
, by definition, it is a Number
).
在此示例中,第9行有效,因為我們可以確定從ArrayList中獲得的任何內容都可以轉換為Number
類型(因為如果它擴展Number
,顧名思義,它就是 Number
)。
But nums.add()
doesn’t work, because we cannot be sure of the “actual type” of the object. All we know is that it must be a Number
or its subtypes (e.g. Integer, Double, Long, etc.).
但是nums.add()
不起作用,因為我們不能確定對象的“實際類型”。 我們所知道的是它必須是一個Number
或其子類型(例如Integer,Double,Long等)。
With contravariance, the converse is true.
在相反的情況下,反之亦然。
Line 9 works, because we can be certain that whatever the “actual type” of the object is, it must be Integer
or its supertype, and thus accept an Integer
object.
第9行行得通,因為我們可以確定,無論對象的“實際類型”是什么,它都必須是Integer
或它的超類型,因此可以接受Integer
對象。
But line 10 doesn’t work, because we cannot be sure that we will get an Integer
. For instance, nums
could be referencing an ArrayList of Objects
.
但是第10行不起作用,因為我們無法確定是否會獲得Integer
。 例如, nums
可以引用Objects
的ArrayList。
應用領域 (Applications)
Therefore, since covariant types are read-only and contravariant types are write-only (loosely speaking), we can derive the following rule of thumb: “Producer extends, consumer super”.
因此,由于協變量類型是只讀的,而協變量類型是只寫的(松散地說),我們可以得出以下經驗法則: “生產者擴展,消費者超級” 。
A producer-like object that produces objects of type T
can be of type parameter <? extends
T>, while a consumer-like object that consumes objects of
type T can be of type parameter <?
super T>.
產生類型T
對象的類似生產者的對象可以是參數<? extends
<? extends
T>,而消費類對象消費
T型可以是參數meter <?
超級T>。
翻譯自: https://www.freecodecamp.org/news/understanding-java-generic-types-covariance-and-contravariance-88f4c19763d2/
泛型型協變逆變