Encountered a problem in the work, the code is described as follows:
Package Test;import Java.util.linkedlist;import Java.util.list;public class Listtest {public void func (List<base> ; List) {} public static void Main (String args[]) {Listtest lt = new Listtest (); list<derived> list = new linkedlist<derived> (); Lt.func (list); Compile error}}class Base {}class Derived extends base {}
Here we need to write a function func, which can take the list of base as a parameter. Originally thought to pass a derived list also can, because derived is base derivation class, that derived list also should be base of list of derived class, result compiler error.
The reasons for this, on the Internet to check some information:Java generics are not covariant.
Generics are both covariant and contravariant, which refers to the ability to use a smaller (less specific) type than the original specified derived type, which refers to a more derived (more specific) type that can be used than the original specified derived type.
Generics in C #, for example, support covariance:
Ienumerable<derived> d = new list<derived> ();ienumerable<base> B = D;
However, Java generics do not support covariant, similar to the above code in Java can not be compiled.
But interestingly, the values in Java support covariance, for example:
integer[] Intarray = new INTEGER[10]; number[] Numberarray = Intarray;
Summary: Generics in Java do not support covariance, much more from a type-safe perspective. This design is not necessarily necessary, for example, C # does not adopt this design. Only the Java designers have made a choice between ease of use and type safety.
Finally back to the original question, to implement a Func-like method, you can modify it to:
public void func (List list) {}
Or with a parameterized type:
Public <T> void func (list<t> List) {}
However, this also has a problem, which blurs the parameter type of func. A better approach is to not change Func, to pass a base-type list at the time of the argument, which requires that the element be transformed into a base type when it is added to the list.
Covariance of generics in Java