泛型型协变逆变_Java泛型类型简介:协变和逆变
泛型型協(xié)變逆變
by Fabian Terh
由Fabian Terh
Java泛型類型簡介:協(xié)變和逆變 (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是一種靜態(tài)類型的語言,這意味著您必須先聲明一個變量及其類型,然后才能使用它。
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.”
定義 :“ 泛型類型是通過類型進行參數(shù)化的泛型類或接口。”
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類定義為接受類型參數(shù)< ; T>,而不是將obj指定為int類型, String類型或任何其他類型。 然后,CA n用t代表在類中的任何一部分泛型類型。
Now, enter covariance and contravariance.
現(xiàn)在,輸入?yún)f(xié)方差和自變量。
協(xié)方差和自變量 (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:
協(xié)方差和協(xié)方差的一個易于記憶(非常非正式)的定義是:
- Covariance: accept subtypes 協(xié)方差:接受子類型
- Contravariance: accept supertypes 矛盾:接受超類型
數(shù)組 (Arrays)
In Java, arrays are covariant, which has 2 implications.
在Java中, 數(shù)組是covariant ,有2個含義。
Firstly, an array of type T[] may contain elements of type T and its subtypes.
首先,類型為T[]的數(shù)組可以包含類型T及其子類型的元素。
Number[] nums = new Number[5];nums[0] = new Integer(1); // Oknums[1] = new Double(2.0); // OkSecondly, an array of type S[] is a subtype of T[] if S is a subtype of T.
其次,類型的數(shù)組S[]是的子類型T[]如果S是的子類型T 。
Integer[] intArr = new Integer[5];Number[] numArr = intArr; // OkHowever, 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 okIt produces a runtime exception, because Java knows at runtime that the “actual object” intArr is actually an array of Integer.
它產生一個運行時異常,因為Java在運行時知道“實際對象” intArr實際上是Integer的數(shù)組。
泛型 (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無法在運行時知道類型參數(shù)的類型信息。 因此,它無法在運行時防止堆污染。
As such, generics are invariant.
因此,泛型是不變的。
ArrayList<Integer> intArrList = new ArrayList<>();ArrayList<Number> numArrList = intArrList; // Not okArrayList<Integer> anotherIntArrList = intArrList; // OkThe type parameters must match exactly, to protect against heap pollution.
類型參數(shù)必須完全匹配,以防止堆污染。
But enter wildcards.
但是輸入通配符。
通配符,協(xié)方差和逆方差 (Wildcards, covariance, and contravariance)
With wildcards, it’s possible for generics to support covariance and contravariance.
使用通配符,泛型有可能支持協(xié)方差和協(xié)方差。
Tweaking the previous example, we get this, which works!
調整前面的示例,我們得到了這個,它有效!
ArrayList<Integer> intArrList = new ArrayList<>();ArrayList<? super Integer> numArrList = intArrList; // OkThe 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.
協(xié)方差和自變量產生一些有趣的結果。 協(xié)變類型是只讀的,而協(xié)變類型是只寫的。
Remember that covariant types accept subtypes, so ArrayList<? extends Number> can contain any object that is either of a Number type or its subtype.
還記得協(xié)變類型接受子類型ArrayList<? extends Numb ,所以ArrayList<? extends Numb ArrayList<? extends Numb ER>可以包含任何對象,或者是of a數(shù)字類型或子類型。
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”.
因此,由于協(xié)變量類型是只讀的,而協(xié)變量類型是只寫的(松散地說),我們可以得出以下經(jīng)驗法則: “生產者擴展,消費者超級” 。
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對象的類似生產者的對象可以是參數(shù)<? extends <? extends T>,而消費類對象消費 T型可以是參數(shù)meter <? 超級T>。
翻譯自: https://www.freecodecamp.org/news/understanding-java-generic-types-covariance-and-contravariance-88f4c19763d2/
泛型型協(xié)變逆變
總結
以上是生活随笔為你收集整理的泛型型协变逆变_Java泛型类型简介:协变和逆变的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孕妇梦到黄牛是什么征兆
- 下一篇: 吹梦到西洲出自哪首诗