Home Help Java G Wildcards in Generics
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Wildcards in Generics

Advertisement
In this section, you will learn the use wildcards or wildcard character 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.


Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 27, 2011

Ask Questions?    Discuss: Wildcards in Generics  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
satish
August 20, 2012
vb.net code

in a number of forms opened in vb.net applications,how can we switch between forms by button click event..pls send example code
DMCA.com