Thursday, October 28, 2010

Wildcards in Generics

We just saw here about generic methods. But how generic are they?
Suppose we have to write a generic method which takes list of elements and prints elements onto screen. Element can be String, Integer,Object...So one can think of using object as type parameter. But this will be a mistake. See here for this.
So solution is wildcards.


The wildcard operator is a solution to the problem explained above.
The character '?' is a wild-card character and it stands for any Java type. It can be java.lang.Object type or some other type. It is just a place-holder that tells that it can be assigned with any type. Considering this case, the following are now valid syntaxes. 

List<?> anyObjects = null; 
List<Integer> integers = new ArrayList<Integer>();
anyObjects = integers;
List<Double> doubles = new ArrayList<Double>();
anyObjects = doubles;

Here is how you write a generic List using the wildcard operator:

List<?> listOfUnknown = new ArrayList<?>();    

Generic method using wildcards
We can now define the printElements() method like this:

public void printElements(List<?> elements){
   for(Object o : elements){
You can call the printElements() with any generified List instance. For instance:
List<String> elements = new ArrayList<String>
// ... add String elements to the list.

When you upcast a List<String> to a List<?> you can now read all elements of the List<?> safely as Object instances. But you still cannot insert elements into the List<?>. The ? could represent any type, and thus it would be possible to insert types that did not match the original definition of the List.

No comments:

Post a Comment