I have never used wildcards in java until i read this.
Let's say I have a super class
List<Vehicle> lstVehicles;
Instead, some people are recommending something like:
List<? extends Vehicle> lstVehicles;
Why should I use wildcards instead of simple generics?
Because Java generics are invariant.
Suppose we have B extends A:
* B is a subtype of A
* an
Since Java arrays are covariant:
*
* an
However, Java generics are invariant:
*
* a
Wildcards are used to make it more flexible while preserving type safety.
*
References:
Wildcards
Generics
Generics and subtyping
More fun with wildcards
0 Comments:
Post a Comment