Thursday, May 27, 2010

Java Wildcards Vs. Generics...

I have never used wildcards in java until i read this.

Let's say I have a super class Vehicle and few sub classes like Scooter, Bike, Car, etc... Now I need to have a list of vehicles, my first thought would be something like:

 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 instanceof B is also an instanceof A

Since Java arrays are covariant:

* B[] is a subtype of A[]
* an instanceof B[] is also an instanceof A[]

However, Java generics are invariant:

* List<B> is NOT a subtype of List<A>
* a instanceof List<B> is NOT an instanceof List<A>.

Wildcards are used to make it more flexible while preserving type safety.

*
List<B> is a List<? extends A> 

References:
Wildcards
Generics
Generics and subtyping
More fun with wildcards

0 Comments: