Wildcards in Generics

In this section, you will learn the use wildcards or wildcard character in Generics.

Wildcards in Generics

Wildcards in Generics

In this section, you will learn the use wildcards or wildcard character in Generics.

Problem :

For better understanding of wildcards, we are taking a scenario :

Take a look at the following code :

List<String> strArrayList = new ArrayList<String>(); 
strArrayList.add(new String("Genrics"));
strArrayList.add(new String("Genrics Wildcards"));

The above code declares a array list of type String and later adding String objects.

Now we declaring another aray list of type String and passing above array list to this :

List<String> anotherStrArrayList  = strArrayList;

This is perfectly alright to pass String array list to another array list of type String.

 But the below code will give compiler error :

List<Object> obj = strArrayList;

The above code will give error because the list of Object type is assigning a list of String type. Though the String is a concrete sub-class of Object, this is assignment is not possible in Generics.

Solution :

Now, the solution of above problem is :

List<?> obj = strArrayList;

The above line is perfectly alright and runs successfully without any error.

The '?' symbol or character is known as wildcard character and it can accept any java type. Whether it is of  type java.lang.Object or String or Integer or any Java type. It acts as placeholder which can be assigned with any Java type.

Other Examples

The below code runs without any error :

List<?> anyObj = null; 

List<Integer> intObj = new ArrayList<Integer>();
anyObj = intObj;

List<Double> doublesObj = new ArrayList<Double>();
anyObj = doublesObj;

In the above code the anyObj has wildcard(?) character in place of type parameter due to which it is possible to assign it any type of list.