Covariance and Contravariance in Java
Let's start with the concept of covariance, contravariance and invariant in Java.
The official argument is that the inversion and covariance describe the inheritance relationship after the type conversion.
Defines a, B, two types, A is a subclass derived from a (a<=b), and F () represents a type conversion such as the new List ();
Covariance: When A<=b, F (A) <=f (B) is established
Inversion: When A<=b, F (B) <=f (A) is established
Unchanged: When A<=b, the above two formulas are not established
So it might be a bit hard to understand, we use code to represent covariance and contravariance.
class Fruit {}class Apple extends Fruit {}class Jonathan extends Apple {}class Orange extends Fruit {}@Testpublic void testArray() { Fruit[] fruit = new Apple[10]; fruit[0] = new Apple(); fruit[1] = new Jonathan(); try { fruit[0] = new Fruit(); } catch (Exception e) { System.out.println(e); } try { fruit[0] = new Orange(); } catch (Exception e) { System.out.println(e); }}
Arrays in Java are covariant, and you can assign array references of base types to arrays of subtypes.
Apple is a fruit subtype, so Apple objects can be assigned to fruit objects. Apple<=fruit Fruit array type is fruit[], this is the new type constructed by the Fruit object, namely F (Fruit), the same, apple[] is the new type that Apple constructs, is f (apple)
So fruit[in the above code] fruit = new APPLE[10] is set up, which is often said in object-oriented programming
A subclass variable can be assigned to a parent class variable, and the parent class variable cannot be assigned to a subclass variable.
Try in the above code: Catch in the compiler will not error, but at run time will be error, because in the compiler array of symbols is fruit type, so can be stored fruit and orange type, but at run time will find the actual type is apple[] type, so will error
Java.lang.ArrayStoreException:contravariant. Testcontravariant$fruit
Java.lang.ArrayStoreException:contravariant. Testcontravariant$orange
Not change
@Testpublic void testList() { List<Fruit> fruitList = new ArrayList<Apple>();}
Such code will be directly on the compiler error. Unlike arrays, generics do not have built-in covariant types, and when generics are used, type information is erased by type at compile time, so generics move this error detection to the compiler. So generics are immutable.
Covariance of generics
But then there will be some very awkward situation, for example, a fruit can be put on the plate inside cannot put apples.
Therefore, in order to solve this problem, Java introduced the wildcard character in generics, so that generics have the properties of covariance and contravariance, and the use of covariant generics is <. Extends fruit>
@Testpublic void testList() { List<? extends Fruit> fruitList = new ArrayList<Apple>(); // 编译错误 fruitList.add(new Apple()); // 编译错误 fruitList.add(new Jonathan()); // 编译错误 fruitList.add(new Fruit()); // 编译错误 fruitList.add(new Object());}
After you have used a generic wildcard, you can actually implement the ArrayList
Because, after defining the fruitlist, the compiler knows only that the type in the container is fruit or its subclass, but what type does not know, the compiler does not know can not histograms on the histograms is not allowed. Analog arrays, in the compiler when the array allows to put fruit and orange in the array of illegal types, but the runtime will still error, generics is to move this check to compile time, the process of covariance lost type information.
So for wildcard characters, T and? The difference is that T is a specific type, but? The compiler does not know what type it is. However, this usage does not affect the value being taken from the container.
list<? Extends fruit> fruitlist = new ArrayList
Fruit Fruit = fruitlist.get (0);
Object object = Fruitlist.get (0);
Compile error
Apple Apple = fruitlist.get (0);
The inverse of a generic type
@Test
public void Testlist () {
list<? Super apple> applelist = new ArrayList
Object object = appleList.get(0); appleList.add(new Apple()); appleList.add(new Jonathan()); // 编译错误 appleList.add(new Fruit()); // 编译错误 appleList.add(new Object());}
You can see that generics can be reversed using super, when you use super to point out that the nether of generics is Apple, you can accept Apple's parent type, and since it's Apple's parent type, the editor knows it's safe to add apple or Apple subclasses to it, so This can be stored in the container, but when the editor knows only the Apple's parent type, what type does not know, so only the value of the compilation error will occur, unless the object type is taken.
The use of generic covariant contravariance
When defining a variable, you must not use the generic wildcard character as in the example above, and the use of the generic wildcard is summarized in the 28th article of effective Jave:
For maximum flexibility, use a wildcard type on the input parameters that represent the producer or consumer. If each input parameter is both a producer and a consumer, then the wildcard type is not good for you: because you need a strict type histograms, which is obtained without any wildcard characters.
Simply put, pecs represents->producer-extends,consumer-super.
Instead of using a wildcard type as the return type, it forces the user to use a wildcard type in client code in addition to providing additional flexibility to the user. Wildcard types should be invisible to the user of the class, which allows the method to accept arguments that they should accept, and rejects arguments that should be rejected, and if the user of the class must consider a wildcard type, the class's API may be faulted.
A classic example is the Copy method in Java.uitl.Collections
public static
if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } }}
Dest for producers to only take data from it, SRC for consumers, only to store data in.
Covariance and Contravariance in Java