Recently have been busy learning to die, digital electricity, make dizzy brain swell, it is rare to squeeze some time tonight to analyze the inverse of Java, covariance. Java introduced the inverse, covariance, and C # slightly different from C #, in Java, the inversion, covariance introduced earlier than C #, so in the form of no C # intuitive (Google launched the JVM-based Kotlin voice, then completely to the C # route). In Java, contravariance, covariance, is more and more intuitive in the use of generic collections (as in C #, usage in Java appears less, but not necessarily).
Use of normal generic collections
The sample code is as follows:
Public Static void Main (string[] args) { ArrayListnew arraylist<>(); Alist.add (new Integer); Alist.add (new Float (10.12)); = Alist.get (0); }
For a alist collection, the generic type parameter number has a qualified type that it can hold. Objects of the Integer/float type can be successfully joined, and can be obtained by getting (note that the type is number). With this example, you can see that the normal generic collection can "access the type of the specification and its subtype object."
Co-change
The following example code:
Public classPerson {} Public classStudentextendsperson{} Public classTeacherextendsperson{} Public Static voidMain (string[] args) {ArrayList<Person> alist =NewArraylist<>(); ArrayList<Student> slist =NewArraylist<>(); //Type Conversion ErrorAlist =slist;}
In Java, the person is the parent of Student, but the generic arraylist<person> is not the parent of arraylist<student>, so alist = Slist type is incompatible. The purpose of the above program is to replace the actual function of alist with slist, so the actual call should be slist corresponding function when using alist later.
In Java to meet the above requirements, there should be 2 conditions:
1. Call Alist.add when putting data (e) To ensure that the parameter E, can be converted to the desired type in Slist.add (e)
2. The results returned by the actual performer Slist.get (index) that called Alist.get when the data was fetched can be converted to the person type declared by alist
The above Condition 2 is established, but the condition 1 does not necessarily set up. Because the Arraylist<person> specification type is person,student, teacher satisfies the requirements of Alist.add (e), but does not satisfy Slist.add (e) requirement that the type must be Student.
Modify the code as follows:
public static void main (string[] args) {ArrayList <? extends Person> alist = new arraylist<> (); ArrayList <Student> slist = new arraylist<> (); // type conversion normal alist = slist; // add data error Alist.add (new Student ()); //normal person p = alist.get (0
Arraylist<student> Slist assigns a value to alist satisfies the generic type parameter constraints.
Alist.add (e) based on? Extend the definition of person, E satisfies the add condition as long as the person type or its subtype, however Slist only allows the Student type object to be joined, so the previously mentioned condition 1 cannot be guaranteed (Null can be added, but it is meaningful).
therefore, in Java (which can be obtained from the previous 2 conditional analyses), a generic or generic collection declared with extends can only be taken from, and cannot be added to, a value.
A collection of extends declarations can only be used to remove elements from it, and a friend may ask, "You can't put a value into it, and then you can take a value fromit." Look at the following code:
Public Static voidMain (string[] args) {ArrayList<Student> slist =NewArraylist<>(); Slist.add (NewStudent ()); ArrayList<Teacher> tlist =NewArraylist<>(); Tlist.add (NewTeacher ()); Test (slist); Test (tlist); } Private Static voidTest (LIST<?extendsPerson>list) { for(person p:list) {System.out.println (p.tostring ()); } }
It is easy to see from the code above that the parameter list of the test method does not allow elements to be added inside the method (except for null), but in main you can add elements to Slist, tlist, and pass them as arguments to the call procedure of the test method. From the point of view of the test method, the parameter list contains the individual person? Student? Teacher? It doesn't matter, it is the absolute type safe to use as a person object. The case in which a subtype of a generic constraint is used as a parent type of a generic constraint is covariant .
Inverse Change
Example code:
Public Static void Main (string[] args) { ArrayListnew arraylist<>(); ArrayListNew arraylist<>(); // slist = alist; }
As the above code intends to use alist substitution slist for element storage, follow the previous analysis of the above code compilation error.
In Java to meet the above requirements, there should be 2 conditions:
1. Call Slist.add when putting data (e) To ensure that the parameter E, can be converted to the desired type in Alist.add (e)
2. The results returned by the actual performer Alist.get (index) that called Slist.get when the data was fetched can be converted to the student type of the Slist declaration
The above Condition 1 is established, but the condition 2 does not necessarily set up. Because the Arraylist<person> specification type is person,student and teacher meet the requirements of Alist.add (e), the Alist.get (index) return value is satisfied with the Slist.get (index The return value must be a requirement of type student.
Modify the code as follows:
Public Static voidMain (string[] args) {ArrayList<Object> alist =NewArraylist<>(); ArrayList<?SuperPerson> slist =NewArraylist<>(); //NormalSlist =alist; Slist.add (NewStudent ()); Slist.add (NewTeacher ()); //ErrorSlist.add (NewObject ()); Object obj= Slist.get (0); }
? Super person indicates that the generic set constraint type assigned to the slist can be as long as super person, so assigning arraylist<object> alist to slist satisfies the generic type parameter constraints.
? The super person indicates that the collection can hold the parent type of person (only accommodating), but the person's inheritance and hierarchy are ambiguous (person from other jar packages). Therefore, the generic constraint has no constraint on the parent type of person, so super prohibits the addition of the person parent type into the collection (which is capable of accommodating but not being allowed) and can only be placed in person and its subtypes.
The Slist.get (index) call actually executes Alist.get (index), and the final return value type is person? Teacher? Student? It is not known, so the generic collection get returned with super declaration can only be of type object.
so in Java (which is the result of the previous 2 conditional analysis), a generic or generic collection that uses super declarations can only be added to it, not from which the value retrieved is Object type and has no meaning.
Also a friend would ask the super declaration of the generic collection only to put no meaning? Look at the following code:
public static void main (string[] args) {ArrayList <Person> alist = new arraylist<> (); Test2 (alist); for (person p:alist) {System.out.print ln (p.tostring ()); }} public static void test2 (list<? super Person> list) {List.add ( new Student ()); List.add ( new Teacher ()); }
It is easy to see from the code above that Alist has a definite type in main and is passed as an argument to the Test2 method's invocation. From the perspective of the Test2 method, you can add a person and its child class object to the collection. The case in which the parent type of a generic constraint is used as a subtype of a generic constraint is contravariant.
Description
The chances of using contravariance and covariance in Java are not too much. If you want to use remember: if the qualified collection can only be put into a value with super, if you want to qualify the collection only to fetch the value when using extends, if the collection needs to both put the value and fetch the value when the standard generic collection is used.
The article writes hastily, if has the improper, please the friend correct.
Java Contravariance and covariance