The wildcard form is when you don't mind what types of objects you are handling.
The generics form allows you to add contraints on the type of objects handled.
An example use case could be the following :
a generic repository with add/update/remove methods, you define common behavior using the generic type :
public class Repository<T>{
public void add(T t){...}
public void update(T t){...}
public void remove(T t){...}
}
Then to make a repository for Apple
and Banana
you just extend this class and replace T with the real type :
public class AppleRepo extends Repository<Apple> {}
public class BananaRepo extends Repository<Banana> {}
If the generic Repository was declared as Repository<?>
, it would not be good because it is not restricted to Banana, and you would not be able to use Banana
specific methods inside it without casting objects;
Also the generics allow you to express further constraints, for example
Repository<T extends Fruit>
allows you to restrict the generic repository class to fruits. And you will be able to make calls to Fruit
methods in its code.
>` is a list which can simultaneously hold lists of different things in it (you can add `List` and `List` into it; but cannot put non`List`s into it). You cannot express this without wildcards, unless perhaps by using raw types. A `List
– newacct Apr 06 '14 at 02:19>` for any `E` can only hold one kind of list inside it: `List`.